我正在使用React.js和TypeScript.有没有办法创建从其他组件继承但有一些额外的道具/状态的React组件?
我想要实现的是这样的:
interface BaseStates {
a: number;
}
class GenericBase<S extends BaseStates> extends React.Component<void, S> {
protected getBaseInitialState(): BaseStates {
return { a: 3 };
}
}
class Base extends GenericBase<BaseStates> {
getInitialState(): BaseStates {
return super.getBaseInitialState();
}
}
interface DerivedStates extends BaseStates {
b: number;
}
class Derived extends GenericBase<DerivedStates> {
getInitialState(): DerivedStates {
var initialStates = super.getBaseInitialState() as DerivedStates; // unsafe??
initialStates.b = 4;
return initialStates
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我把这个会失败this.setState中Derived,我得到一个错误的打字稿(类型的参数DerivedStates是不能分配给类型S).我想这不是特定于TypeScript的东西,而是将继承与泛型混合的一般限制(?).这有什么类型安全的解决方法吗?
UPDATE …
我正在尝试编写一个抽象的 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
};
}
}
Run Code Online (Sandbox Code Playgroud)
......并且还制作了一个Cat扩展它的类:
import * …Run Code Online (Sandbox Code Playgroud)