简体   繁体   English

在React组件中向this.props.children添加自定义道具

[英]Add custom props to this.props.children in React component

I have component which accepts children. 我有接受孩子的组件。 Let's say; 我们说吧;

<Toolbar><div>C1</div><div>C2</div></Toolbar>

When I print children using {children} inside of Toolbar , I can see them. 当我使用Toolbar {children}打印孩子时,我可以看到它们。 However, I need to add/manupilate some props, so I want to iterate over them (like other arrays.map). 但是,我需要添加/ manupilate一些道具,所以我想迭代它们(像其他arrays.map)。 However, when I try to use children.map I get following error. 但是,当我尝试使用children.map我得到以下错误。

Warning: React.createElement: type is invalid -- expected a string (for built-in 
components) or a class/function (for composite components) but got: object.

How can I achive this? 我怎么能得到这个?

Thank you! 谢谢!

Edit; 编辑; I mean something like; 我的意思是;

{children.map((Child,index)=> <Child {...newProps}/>)}

You would make use of React.Children.map and then React.cloneElement to return the children after adding new props 你会利用React.Children.map然后React.cloneElement增加新的道具后,孩子恢复

    {React.Children.map(children, child => {
                return React.cloneElement(child, {
                    ...newProps
                });
            })}

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

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