繁体   English   中英

根据组件类型有条件地将道具传递给孩子

[英]Conditionally pass props to child based on component type

我对React还是相当陌生,并且正在创建一个使用react-bootstrap的表单字段的简单工具集。 我正在使用<Form>组件包装所有内容。 <Form>组件将呈现所有子项,并传递一个新属性。

React.Children.map(this.props.children, (child) => {
    return React.cloneElement(child, {
        myNewProp: 'hello'
    }
});

我的问题是没有myNewProp子元素会导致警告Unknown props myNewProp ,本地HTML和react-bootstrap组件。 是否有任何方法可以根据组件的类型有条件地向子元素添加道具? 例如

if (child instanceof <nativeHTMLelement>) { ... } else { ... }

在这种情况下,您可以使用child.type

if (typeof child.type === 'string') {
  // this is a html element
} else {
  // this is a React component
}

假设您有isNumberisString

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'
        }
});

如果您使用的是打字稿,则isNumberisString应该由@types/node 如果不是,它们很容易实现。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM