通过道具渲染组件时继承道具类型

时间:2019-07-20 14:27:16

标签: javascript reactjs typescript

通过父项prop渲染组件时,是否可以继承prop-type?假设我们无法直接访问“ ChildProps”和“ Props”界面?

父组件

interface ChildProps {
  counter: number;
  setCounter: React.Dispatch<React.SetStateAction<number>>;
}

interface Props {
  child: React.ElementType<ChildProps>;
}

function Parent({ child: Child }: Props) {
  const [counter, setCounter] = React.useState(0);

  return (
    <div>
      <Child counter={ counter } setCounter={ setCounter } />
    </div>
  );
}

子组件

function Child(props) {
  return (
    <div>
      // 'counter' is missing in props validation eslint(react/prop-types)
      <p>{ props.counter }</p>

      // 'setCounter' is missing in props validation eslint(react/prop-types)
      <button onClick={ () => props.setCounter(props.counter + 1) }>
        inc
      </button>
    </div>
  );
}

1 个答案:

答案 0 :(得分:0)

杰克

在React中,您不应真正从React.Component以外的类中进行 extend / inherit 扩展,这是我们在 React <中遵循的唯一约定/ em>编写组件。

功能组合是我们进行抽象处理的方式,例如:编写HOC为其他任何组件提供某种方法或属性。

const withAdditionalProps = (someProps) => WrappedComponent => (
  class NewWrappedComponent extends React.Component {
    givenMethod = () => { /* some algorithm */ }

    render(){
      const newProps = { ...this.props, givenMethod: this.givenMethod  }
      return (
        <WrappedComponent {...newProps}>
          {this.props.children}
        </WrappedComponent>
      );
    };
  }
);

我希望这一点或其中一部分是合理的。