首页 > 解决方案 > 如何在覆盖父函数的函数中访问子类中的 this.props

问题描述

我想this.props.childName在父函数中定义的子函数中使用。但它是 TypeScript 编译错误 ( Property 'name' does not exist...) 如果我使用this.props.parentName,就可以了。如何访问this.props子类?

interface Prop<T> {
  parentName: string
}

class Parent<T> extends React.Component<Prop<T>, State<T>> {
  constructor(props: Prop<T>) {
    super(props)
  }
  printName() {}
}

interface PropChildren<T> {
  childName: string
}

class Child<T> extends Parent<string> {
  constructor(props: PropChildren<T>) {
    super(props)
  }

  printName() {
    console.log(this.props.childName) // here I want to use children prop but compile error
  }
}

标签: javascriptreactjstypescript

解决方案


你的子组件扩展了父组件,而父组件中的 props 类型是Prop<T>,其中只包含 property parentName

为了让 PropChildren 作为子组件中的道具类型,您应该将其声明为:

class Child<T> extends React.Component< PropChildren<T>, State<T>> {
    // ...
}

顺便说一句,您不需要使您的道具接口通用(使用<T>)。仅当接口可以在具有不同数据类型的不同上下文中使用时才使用泛型。

根据您的评论,这是一个示例,说明您如何与孩子分享父母的行为,但仍然能够为孩子的道具定义不同的数据类型:

interface PropParent {
    parentName: string
}

class Parent<TProp extends PropParent> extends React.Component<TProp, State> {
    constructor(props: TProp) {
        super(props)
    }
    printName() {}
}

interface PropChildren extends PropParent {
    childName: string
}

class Child<T> extends Parent<PropChildren> {
    constructor(props: PropChildren) {
        super(props)
    }

    printName() {
        console.log(this.props.childName)
    }
}

推荐阅读