我这样写了一个 BaseListPage
组件:
export default class BaseListPage extends Component<Props, State> {
而且,我想写另一个组件继承BaseListPage
,像这样:
export default class DynamicListPage extends BaseListPage<Props, State> {
但是提示Type 'BaseListPage' is not generic.
。
我是react-native的新打字员,请帮忙!
最佳答案
这是因为你将类型参数传递给你的 BaseListPage
类与 BaseListPage<Props, State>
的一部分 class DynamicListPage extends BaseListPage<Props, State>
, 但该类不接受任何类型参数。
你可以让BaseListPage
通过使其成为“通用”来获取类型参数:
class BaseListPage<Props, State> extends Component<Props, State> {
参见 - https://www.typescriptlang.org/docs/handbook/generics.html
由于 React 组件可以具有任何形状的 props 或状态,这些类型参数允许您准确定义它们对于类的给定实例的外观,允许您运行必要的类型检查。
例如。
interface Props {
foo: string
}
class MyComponent extends Component<Props> {
render() {
console.log(this.props.foo) // Fine
console.log(this.props.bar) // Error
...
}
}
因此,要么定义一个 BaseListPage
的确切 Props 和 State组件可以像这样,从而消除了对它的通用性的需要:
interface BaseListPageProps {
foo: string
}
interface BaseListPageState {
bar: string
}
class BaseListPage extends Component<BaseListPageProps, BaseListPageState> {
...
}
class DynamicListPage extends BaseListPage {
render() {
console.log(this.props.foo) // Fine
console.log(this.state.bar) // Fine
console.log(this.props.bar) // Error
...
}
}
或者让它是通用的,允许 DynamicListPage 决定 Props 和 State 类型:
class BaseListPage<Props, State> extends Component<Props, State> {
...
}
interface DynamicListPageProps {
foo: string
}
interface DynamicListPageState {
bar: string
}
class DynamicListPage extends BaseListPage<DynamicListPageProps, DynamicListPageState> {
更好的是,通过组合而不是继承来组合。 https://reactjs.org/docs/composition-vs-inheritance.html
关于javascript - 如何使用 typescript 继承 native react 组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59168793/