问题描述
我有一个功能组件,该组件将组件作为道具。该组件始终具有绑定到其的静态方法,但不仅限于一种类型。如何输入检查道具?
const ElementA = () => { return <></> }
ElementA.staticCallable = (instance) => {}
const ElementB = () => { return <></> }
ElementB.staticCallable = (instance) => {}
const Component = ({ e }) => {
const someVal = e.type.staticCallable(e)
return <>{stuffWith(someVal)}</>
}
Component.propTypes = {
e: PropTypes.shape({
type: PropTypes.shape({
staticCallable: PropTypes.func.isrequired
}).isrequired,}).isrequired,}
这里的问题是type
不是对象,而是react元素。如此有效:
Component.propTypes = {
e: PropTypes.shape({
type: PropTypes.elementType.isrequired,}
但是,这不能检查我是否具有静态成员。我该怎么办?
作为参考,这是我父母的样子:
const Parent = () => {
const ea = <ElementA />
const eb = <ElementB />
return <>
<Component e={ea} />
<Component e={eb} />
</>
}
解决方法
通读了github.com/facebook/prop-types上的文档后,我发现了这一点:
// 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.'
);
}
},
我以前从未见过/matchme/
语法,但是我想出了一些可行的方法:
const elementShape = PropTypes.shape({
type: (props,componentName) => {
PropTypes.checkPropTypes(
{
staticCallable: PropTypes.func,},props[propName],"static member",componentName
)
},})
Component.propTypes = {
e: elementShape.isRequired,}
将getConnectPoint: PropTypes.func,
更改为bool会发出警告:
警告:失败的静态成员类型:提供给
staticCallable
的{{1}}类型的function
无效的静态成员Component
在这种情况下,“静态成员”字符串显得笨拙,但类型检查仍在起作用。