Tengo un componente <Button>
.
Si el componente no tiene this.props.children
, quiero configurar prop ariaLabel
como isRequired
, de lo contrario, puede ser opcional. ¿Cómo puedo hacer eso?
ariaLabel
prop no requerido:
<Button>Add to bag</Button>
ariaLabel
prop tiene que ser requerido:
<Button ariaLabel="Add to bag" icon={ favorite } />
si this.props.children
y this.props.ariaLabel
están vacíos, arroja un error que dice que 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 */ };
Gracias
No necesita otra biblioteca, 'prop-types' proporciona esto de forma inmediata. Consulte https://facebook.github.io/react/docs/typechecking-with-proptypes.html
Ejemplo:
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!'); } }, }
Esto puede ser exactamente lo que necesita: https://github.com/thejameskyle/react-required-if
En tu caso, tus propTypes serían:
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 */ };
Para agregar a la respuesta anterior de @chickenchilli, puede abstraer esto en una función de ayuda más útil como esta:
export default function conditionalPropType(condition, message) { if(typeof condition !== 'function') throw "Wrong argument type 'condition' supplied to 'conditionalPropType'"; return function(props, propName, componentName) { if (condition(props, propName, componentName)) { return new Error(`Invalid prop '${propName}' '${props[propName]}' supplied to '${componentName}'. ${message}`); } } }
import PropTypes from 'prop-types'; import conditionalPropType from './conditionalPropType'; [...] MyComponent.propTypes = { conditionProp: PropTypes.bool, dependentProp: conditionalPropType(props => (props.condition && typeof(props.someProp) !== 'boolean'), "'dependentProp' must be boolean if 'conditionProp' is true"), };