我正在尝试编写一个抽象的 ReactJS 类,然后对其进行扩展。因此,我需要扩展它的props
和state
(据我所知;我是 React 的新手)。
根据Nitzan展示如何props
从基类扩展的帖子,我创建了一个抽象类Animal
:
import * as React from "react";
export interface AnimalProps {
isHibernatory: boolean;
}
export interface AnimalState {
shouldHibernate: boolean;
}
// TS2322: Type '{ shouldHibernate: boolean; }' is not assignable to type 'Readonly<S>'.
export abstract class Animal<P extends AnimalProps, S extends AnimalState>
extends React.Component<P, S> {
constructor(props: P) {
super(props);
this.state = {
shouldHibernate: props.isHibernatory
};
}
}
......并且还制作了一个Cat
扩展它的类:
import * as React from "react";
import {AnimalProps, AnimalState, Animal} from "./Animal";
export interface CatProps extends AnimalProps {
isHairless: boolean;
}
export interface CatState extends AnimalState {
shouldSeekWarmth: boolean;
}
export class Cat extends Animal<CatProps, CatState> {
constructor(props: P) {
super(props);
this.state = {
willHibernate: props.isHibernatory,
shouldSeekWarmth: props.isHairless
};
}
}
但是,正如所评论的,TypeScript 编译器会抛出错误TS2322: Type '{ shouldHibernate: boolean; }' is not assignable to type 'Readonly<S>'
。我相信这是因为它不能保证S
一旦扩展就会是只读的AnimalState
。我还能怎么写这个?还是我错过了更大的图景?