我有一个可以克隆child并为其传递一些新道具的组件。在我的PropTypes中,我只想允许一个React组件,而不能允许其他任何组件。例如:
<PartentComponent>
<ChildContent/>
</PartentComponent>
它并不总是被称为ChildContent,它可以是组件的任何名称。
我不希望parentComponent允许除组件之外的任何东西。这是不允许的。
<PartentComponent>
<div>content</div>
</PartentComponent>
我尝试使用PropType元素在ParentComponent中使用。但这仍然接受div
Modal.propTypes = {
children: PropTypes.element,
};
我除了组件之外什么都不想要的原因是,我在不可以在div上使用的cloneElement中传递了道具。
const childComponent = React.Children.map(children, child =>
cloneElement(child, {
end: onEndProcesss,
}));
{React.Children.only(this.props.children)}
验证子代只有一个子代(一个React元素)并返回它。否则,此方法将引发错误。
import React from 'react'
function Modal() {
return(
{React.Children.only(this.props.children)}
)
}
Modal.propTypes = {
children: PropTypes.element,
};
您无法使用“本地” PropTypes API进行操作。但是您可以创建自己的验证器。您可以从react.element的type
属性中解开组件类型。 https://github.com/facebook/react/blob/master/packages/react/src/ReactElement.js#L118
如果typeof element.type是字符串,则需要引发错误
原型类型检查器的示例,您可以在这里找到:https://github.com/facebook/prop-types/blob/master/factoryWithTypeCheckers.js#L273