2017-02-17 61 views
7

我有一个组件<Button>
如果组件没有this.props.children,我想设置道具ariaLabelisRequired,否则可以是可选的。我怎么做?不需要反应道具 - 如果另一个道具为空/空,则需要一个道具

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

感谢

+1

你需要像https://github.com/evcohen/react-proptype-conditional-require做的propTypes对象。 – Joe

回答

6

这可能正是你所需要的: https://github.com/thejameskyle/react-required-if

在你的情况,你的propTypes是:

import requiredIf from 'react-required-if'; 

Button.propTypes = { 
    /** icon inside Button. */ 
    icon: React.PropTypes.object, 
    /** Content inside button */ 
    children: React.PropTypes.node, 
    /** Aria-label to screen readers */ 
    ariaLabel: requiredIf(React.PropTypes.string, props => !props.children), /*isRequired if children is empty */ 
}; 
+0

yhp,它的工作! thnsk –

+0

为什么在这里使用第三方! – jalal246

21

你并不需要另一个库,“丙类”提供了这种开箱即用。 见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!'; 
      ); 
     } 
    }, 

} 
+3

这就是我一直在寻找的。我不想要另一个依赖。 – grammar

+1

考虑到'prop-types'确实可以做到这一点,这显然是最好的答案。 – kylebebak

+0

有没有一种很好的方法在这里面使用propTypes窗体?我正在考虑诸如'node'或'shapeOf(...)'之类的东西,其中测试适度复杂地写出来。 –