【发布时间】:2015-09-30 12:47:49
【问题描述】:
我正在使用带有 TypeScript 的 React.js。有什么方法可以创建继承自其他组件但具有一些额外道具/状态的 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
}
}
但是,如果我在 Derived 中调用 this.setState,这将失败,我收到 TypeScript 错误(DerivedStates 类型的参数不可分配给 S 类型)。我想这不是 TypeScript 特有的东西,而是将继承与泛型混合的一般限制(?)。是否有任何类型安全的解决方法?
更新
我确定的解决方案(基于 David Sherret 的回答):
interface BaseStates {
a: number;
}
class GenericBase<S extends BaseStates> extends React.Component<void, S> {
constructor() {
super();
this.state = this.getInitialState();
}
getInitialState(): S {
return { a: 3 } as S;
}
update() {
this.setState({ a: 7 } as S);
}
}
interface DerivedStates extends BaseStates {
b: number;
}
class Derived extends GenericBase<DerivedStates> {
getInitialState(): DerivedStates {
var initialStates = super.getInitialState();
initialStates.b = 4;
return initialStates;
}
update() {
this.setState({ a: 7, b: 4 });
}
}
【问题讨论】:
-
我也很难找到答案。基本上我想要的是将
A<DerivedProps>组件传递给A<BaseProps>接口,以在A内部和外部进行一些基本的道具类型检查。 -
但后来我发现情况类似于将
DerivedProps => void分配给BaseProps => void。第一个函数(或类构造函数)不能继承第二个。 -
考虑使用
abstract类/函数。 (see answer below)
标签: oop generics inheritance reactjs typescript