javascript - 如何使用 typescript 继承 native react 组件?

标签 javascript reactjs typescript native

我这样写了一个 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/

相关文章:

javascript - Node.js 文档字数统计输出在元素 id 中

javascript - Youtube 播放器 API 差异(Chromeless 与 IFrame)- 哪个更好?

ios - react native : Refs in ListView

android - 仅学习 React Native 是否足以构建 iOS 和 Android 应用程序?

typescript - 类型 'user' 上不存在属性 'DefaultRootState'

reactjs - 基于 Typescript 的 React : importScripts() gives: 'importScripts' is not defined no-undef

javascript - 试图在 javascript 中更改光标

每分钟数据的javascript图表库

javascript - gatsby上的CSS和JS文件丢失

javascript - React TypeScript 如何遍历一个对象?