简体   繁体   中英

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. However, I need to add/manupilate some props, so I want to iterate over them (like other arrays.map). However, when I try to use children.map I get following error.

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(children, child => {
                return React.cloneElement(child, {
                    ...newProps
                });
            })}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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