【问题标题】:How to declare different state and props for subclasses on react with typescript如何在与打字稿反应时为子类声明不同的状态和道具
【发布时间】:2018-06-15 12:56:50
【问题描述】:

对于 React 的 typescript 和静态类型来说是超级新手,所以

鉴于我有这个父组件:

interface ParentProps {
 something: string
}

interface ParentState {
 somethingElse: string
}

export default class ParentComponent extends React.Component<ParentProps, ParentSate> {

  // Component Logic.

  sharedFunction() {
    // Some shared function.
  }
}

如何在子组件上声明不同的 props 和 state,例如:

interface ChildProps {
 something: string
}

interface ChildState {
 somethingElse: string
}

export default class ChildComponent extends ParentComponent<ChildProps, ChildState> {
  // Child component logic.
}

当我尝试上述方法时,我得到:

[ts] Type 'ParentComponent' is not generic.

那么,实现这种分离的最佳方法是什么?谢谢。

【问题讨论】:

  • 一般来说不建议你扩展自定义的 React 组件,建议你使用组合而不是继承。那里有关于原因的信息。这是官方 React 文档中关于用组合替换继承的页面:reactjs.org/docs/composition-vs-inheritance.html
  • 谢谢@Jayce444 我已经阅读了文档,并且我确实相信我应该首先解决我原来的问题。

标签: reactjs typescript


【解决方案1】:

您也可以将ParentComponent 设为通用,以便ChildComponent 可以指定不同的道具和状态:

interface ParentProps {
    something: string
}

interface ParentState {
    somethingElse: string
}

export class ParentComponent<TProps extends ParentProps = ParentProps, TState extends ParentState = ParentState>
extends React.Component<TProps, TState> {

    // Component Logic.

    sharedFunction() {
        // Some shared function.
    }
}

interface ChildProps {
    something: string
}

interface ChildState {
    somethingElse: string
}

export class ChildComponent extends ParentComponent<ChildProps, ChildState> {
    // Child component logic.
}

【讨论】:

    猜你喜欢
    • 2016-08-13
    • 2018-10-26
    • 2022-11-02
    • 2021-05-10
    • 1970-01-01
    • 2021-09-12
    • 2021-11-22
    • 2020-12-24
    • 2021-02-23
    相关资源
    最近更新 更多