我至少需要做以下一项道具:
MyComponent.propTypes = { data: PropTypes.object, url: PropTypes.string };
因此,在上面的示例中,必须提供data或urlprop。这里的用例是用户可以提供data或url。如果url提供,则组件将获取data。
data
url
额外的问题:我该怎么做至少一个道具而不是一个道具?
PropTypes实际上可以将自定义函数作为参数,因此您可以执行以下操作:
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}'.`); } } }
允许客户进行错误消息传递。使用此方法时只能返回null或Error
您可以在这里找到更多信息
https://facebook.github.io/react/docs/typechecking-with- proptypes.html#react.proptypes
来自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.' ); } },