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



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

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

我遇到的问题是,没有myNewProp道具的子元素会导致警告Unknown props myNewProp,本机HTML和反应引导组件。有没有办法根据组件的类型有条件地将 props 添加到子元素?例如

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 提供。如果你不是,它们很容易实现。

最新更新