我有一个组件<Button>
如果组件没有this.props.children,我想将prop ariaLabel设置为isRequired,否则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 */
};

谢谢

最佳答案

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

}

07-28 05:37