【发布时间】:2019-12-16 15:38:12
【问题描述】:
我有一个扩展另一个组件的组件类,我正试图弄清楚如何覆盖我从中继承的状态的类型。
这是一个例子:
class MyComponent extends React.Component<SomeProps, SomeState> {
// ...
}
class ExtendedComponent extends MyComponent {
// How to overwrite SomeState?
// This component needs to store a different model of state.
}
我需要ExtendedComponent 为其interface 使用不同的state,但我不知道如何实现这一点。
编辑:现在去某个地方!
但是,现在Parent 充满了与状态修改有关的各种错误。到目前为止,这是我所得到的:
interface ParentProps {
a: string;
}
interface ParentState {
b: string;
}
class Parent<P, S> extends React.Component<ParentProps & P, ParentState & S> {
constructor(props) {
super(props);
// Type '{ b: "hello"; }' is not assignable to type 'Readonly<ParentState & S>'
this.state = {
b: 'hello',
};
}
aFunction(): void {
/*
Argument of type '{ b: "testing"; }' is not assignable to parameter of type '(ParentState & S) | ((prevState: Readonly<ParentState & S>, props: Readonly<ParentProps & P>) => (ParentState & S) | Pick<ParentState & S, "b">) | Pick<ParentState & S, "b">'.
Type '{ b: "testing"; }' is not assignable to type 'Pick<ParentState & S, "b">'.
Types of property 'b' are incompatible.
Type '"testing"' is not assignable to type 'string & S["b"]'.
Type '"testing"' is not assignable to type 'S["b"]'.
*/
this.setState({
b: 'testing',
});
}
}
interface ChildProps {
c: string;
}
interface ChildState {
d: string;
}
class Child extends Parent<ChildProps, ChildState> {
constructor(props) {
super(props);
// This is what I'm after -- and TypeScript doesn't complain :)
this.state = {
b: 'hello',
d: 'world',
};
}
}
编辑 2:
近两年后回想起来:
由 React 的维护者扩展另一个组件类 is not recommended。这是有充分理由的,因为我必须在糟糕的生产应用程序中维护这种方法!我最终使用高阶组件和自定义钩子重写了很多代码。
这个用例没有得到很好的支持是有原因的,避免因过度设计组件而导致复杂化!想象一下,试图向另一位开发人员解释你纠结的继承问题。
仅仅因为它听起来很酷并且您可以做到,并不意味着您应该这样做。我强烈建议使用功能组件,如果您需要共享功能,请使用higher-order functions 和/或custom hooks。
【问题讨论】:
-
您最终找到解决方案了吗?
-
@Luze 不幸的是,没有。如果你发现了什么,请告诉我!
标签: reactjs typescript generics overwrite