问题
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