React props - 如果另一个prop为null / empty,则在prop上设置isRequired [英] React props - set isRequired on a prop if another prop is null / empty
问题描述
我有一个组件< Button>
。
如果组件没有 this.props.children
,我想将prop ariaLabel
设置为 isRequired
,否则可以是可选的。我该怎么办?
I have a component <Button>
.
If the component doesn't has this.props.children
, I want to set the prop ariaLabel
as isRequired
, otherwise in can be optional. How do I do that?
ariaLabel
道具不需要:
ariaLabel
prop not required:
<Button>Add to bag</Button>
ariaLabel
必须要求支柱:
ariaLabel
prop has to be required:
<Button ariaLabel="Add to bag" icon={ favorite } />
如果 this.props.children
和 this.props.ariaLabel
为空,它会抛出一个错误,说 this.props。 ariaLabel
是 isRequired
if this.props.children
and this.props.ariaLabel
are empty, it throws an error saying that this.props.ariaLabel
is isRequired
<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
You don't need another library, 'prop-types' provides this out of the box. See 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!';
);
}
},
}
这篇关于React props - 如果另一个prop为null / empty,则在prop上设置isRequired的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!