PropTypes actually can take a custom function as an argument so you could do something like this:
MyComponent.propTypes = {
data: (props, propName, componentName) => {
if (!props.data && !props.url) {
return new Error(`One of props 'data' or 'url' was not specified in '${componentName}'.`);
}
},
url: (props, propName, componentName) => {
if (!props.data && !props.url) {
return new Error(`One of props 'url' or 'data' was not specified in '${componentName}'.`);
}
}
}
which allows for customer Error messaging. You can only return null or an Error when using this method
You can find more info on that here
https://facebook.github.io/react/docs/typechecking-with-proptypes.html#react.proptypes
from the react docs:
// You can also specify a custom validator. It should return an Error
// object if the validation fails. Don't `console.warn` or throw, as this
// won't work inside `oneOfType`.
customProp: function(props, propName, componentName) {
if (!/matchme/.test(props[propName])) {
return new Error(
'Invalid prop `' + propName + '` supplied to' +
' `' + componentName + '`. Validation failed.'
);
}
},
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…