我有一个组件<Button>。 如果组件没有this.props.children,我想将prop设置ariaLabel为isRequired,否则in可以是可选的。我怎么做?
<Button>
this.props.children
ariaLabel
isRequired
ariaLabel 不需要道具:
<Button>Add to bag</Button>
ariaLabel 需要道具:
<Button ariaLabel="Add to bag" icon={ favorite } />
如果this.props.children和this.props.ariaLabel为空,则抛出错误,说this.props.ariaLabel是isRequired
this.props.ariaLabel
<Button icon={ favorite } />
propTypes:
Button.propTypes = { /** icon inside Button. */ icon: React.PropTypes.object, /** Content inside button */ children: React.PropTypes.node, /** Aria-label to screen readers */ ariaLabel: React.PropTypes.string, /*isRequired if children is empty */ };
谢谢
您不需要其他库,“ prop- types”提供了现成的功能。参见https://facebook.github.io/react/docs/typechecking-with- proptypes.html
例:
import PropTypes from 'prop-types'; //....... ExampleComponent.propTypes = { showDelete: PropTypes.bool, handleDelete: function(props, propName, componentName) { if ((props['showDelete'] == true && (props[propName] == undefined || typeof(props[propName]) != 'function'))) { return new Error('Please provide a handleDelete function!'); } }, }