Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何在react with typescript上为子类声明不同的状态和道具_Reactjs_Typescript - Fatal编程技术网

Reactjs 如何在react with typescript上为子类声明不同的状态和道具

Reactjs 如何在react with typescript上为子类声明不同的状态和道具,reactjs,typescript,Reactjs,Typescript,超级新的typescript和静态类型一般都有React,所以 鉴于我有这个父组件: interface ParentProps { something: string } interface ParentState { somethingElse: string } export default class ParentComponent extends React.Component<ParentProps, ParentSate> { // Component L

超级新的typescript和静态类型一般都有React,所以

鉴于我有这个父组件:

interface ParentProps {
 something: string
}

interface ParentState {
 somethingElse: string
}

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

  // Component Logic.

  sharedFunction() {
    // Some shared function.
  }
}
那么,实现这种分离的最佳方法是什么呢?谢谢。

您也可以将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.
}

一般来说,不建议您扩展自定义React组件,建议您使用组合而不是继承。有关于原因的信息。这里是官方React文档中关于用合成取代继承的一页:谢谢@Jayce444我已经阅读了该文档,我相信这是我首先应该解决我最初的问题的方式。
[ts] Type 'ParentComponent' is not generic.
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.
}