React 组合组件属性类型

Vic*_*Vic 3 reactjs react-proptypes

我正在使用组合模式进行反应。例如,我有这个简单的组件:

class Simple extends React.Component {
  render() {
    return <div>{this.props.text}</div>;
  }
}

Simple.propTypes = {
  text: React.PropTypes.string.isRequired
};
Run Code Online (Sandbox Code Playgroud)

现在,我有了这个增强的组件:

class Enhanced extends React.Component {
  render() {
    return (
      <div>
        <div>Hi, I'm the enhanced version</div>
        <Simple {...this.props} />
      </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

现在,我如何指定增强组件的 proptypes?我可以这样做:

Enhanced.propTypes = {
  text: React.PropTypes.string.isRequired
};
Run Code Online (Sandbox Code Playgroud)

但这不好,因为我必须列出Simple组件的所有道具,并且每当我更改这些道具时,我都必须更改它们Enhanced

azi*_*ium 5

propTypes只是普通的 JS 对象。您可以随心所欲地编写它们:

// Simple.js
export const simplePropTypes = {
  text: React.PropTypes.string.isRequired
}

Simple.propTypes = simplePropTypes

// Enhanced.js
import Simple, { simplePropTypes } from './Simple'

Enhanced.propTypes = {
  somethingElse: React.PropTypes.number,
  ...simplePropTypes
}
Run Code Online (Sandbox Code Playgroud)

更新

应该能够直接使用组件定义propTypes

Enhanced.propTypes = {
  somethingElse: React.PropTypes.number,
  ...Simple.propTypes
}
Run Code Online (Sandbox Code Playgroud)