有条件地根据组件类型将props传递给child

时间:2017-01-11 11:40:31

标签: javascript reactjs

我对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 { ... }

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

假设您有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'
        }
});

如果您使用的是打字稿,则isNumber应提供isString@types/node。如果你不是,他们很容易实现。