React composition component proptypes

依然范特西╮ 提交于 2019-12-12 13:55:06

问题


I'm using the composition pattern for react. So, for example, I have this simple component:

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

Simple.propTypes = {
  text: React.PropTypes.string.isRequired
};

Now, I have this enhanced component:

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

Now, how can I specify the proptypes for the enhanced component? I could do this:

Enhanced.propTypes = {
  text: React.PropTypes.string.isRequired
};

but that's not good because I'll have to list all the props of Simple component and anytime I change those props, I'll have to change them in Enhanced


回答1:


propTypes are just normal JS objects. You can compose them however you like:

// 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
}

update:

You should be able to use the component definition's propTypes directly.

Enhanced.propTypes = {
  somethingElse: React.PropTypes.number,
  ...Simple.propTypes
}


来源:https://stackoverflow.com/questions/41703724/react-composition-component-proptypes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!