我正在使用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
}
}
但是,如果我在 Derived
中调用 this.setState
,则会失败,我收到TypeScript错误( DerivedStates
类型的参数不能分配给 S
类型) . 我想这不是特定于TypeScript的东西,而是将继承与泛型混合的一般限制(?) . 这有什么类型安全的解决方法吗?
UPDATE
我解决的解决方案(根据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 });
}
}
1 回答
您可以使用类型断言在
Derived
中一次性设置状态的一些属性:顺便说一下,
getInitialState
不需要有不同的名字......你可以这么做: