小编典典

反应道具-如果另一个道具为空/空,则在道具上设置isRequired

reactjs

我有一个组件<Button>
如果组件没有this.props.children,我想将prop设置ariaLabelisRequired,否则in可以是可选的。我怎么做?

ariaLabel 不需要道具:

<Button>Add to bag</Button>

ariaLabel 需要道具:

<Button ariaLabel="Add to bag" icon={ favorite } />

如果this.props.childrenthis.props.ariaLabel为空,则抛出错误,说this.props.ariaLabelisRequired

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

谢谢


阅读 327

收藏
2020-07-22

共1个答案

小编典典

您不需要其他库,“ 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!');
        }
    },

}
2020-07-22