我对React相当新,我正在创建一个使用react-bootstrap的表单字段的简单工具集。我正在使用<Form>
组件来包装所有内容。<Form>
组件将呈现所有子项,并传递新属性。
React.Children.map(this.props.children, (child) => {
return React.cloneElement(child, {
myNewProp: 'hello'
}
});
我遇到的问题是那些不具有myNewProp
道具的子元素会产生警告Unknown props myNewProp
,本机HTML和反应引导组件。有没有办法根据组件的类型有条件地将子句添加到子元素? E.g。
if (child instanceof <nativeHTMLelement>) { ... } else { ... }
答案 0 :(得分:0)
在这种情况下,您可以使用child.type
:
if (typeof child.type === 'string') {
// this is a html element
} else {
// this is a React component
}
答案 1 :(得分:0)
假设您有isNumber
和isString
:
React.Children.map(this.props.children, (child) => {
if(!child)
return child;
if(isNumber(child))
return child;
if(isString(child))
return child;
// then this must be a ReactElement
if(child.type === MyElement)
return React.cloneElement(child, {
myNewProp: 'hello'
}
});
如果您使用的是打字稿,则isNumber
应提供isString
和@types/node
。如果你不是,他们很容易实现。