问题描述
我想使用元素子代的道具,并希望验证这些道具。
是否可以使用prop-types
来实现?
export default function MyComponent(props) {
return (
<div>
{React.Children.map(props.children,(c,i) => {
// Want to do something with validated c.props.somePropThatNeedValidation (if exists of course)
// c Is not an element that I wrote so I can't validate it there
{React.cloneElement(c,{extras})}
}
)}
</div>
)
}
MyComponent.propTypes = {
children: PropTypes.node,.
.
.
}
解决方法
简短的回答,是的,但您可能不应该这样做。 :)
道具类型用于定义组件的合同。有点像静态类型为您所做的事情(例如Typescript)。如果您确实想验证children
道具,则可以编写一个自定义验证器来验证。来自the 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.'
);
}
},
您可以为孩子的道具做类似的事情(只需将customProp
替换为children
,然后根据需要进行验证。
^^话虽如此,我强烈建议您不要这样做,除非绝对必要! children
道具是React世界中一个众所周知的特殊意图的道具。由于prop-type实际上仅用于开发人员的健康检查,因此,最好花几分钟时间为组件编写可靠的单元测试。
我能想到的唯一有效的情况是,如果您正在提供一个框架,并希望为您的使用者提供有用的调试消息。但是,好的文档和示例通常比控制台警告FWIW有更多的支腿。
让我知道我是否不明白你的意图。