最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Add custom props to this.props.children in React component - Stack Overflow

programmeradmin6浏览0评论

I have ponent 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 
ponents) or a class/function (for posite ponents) but got: object.

How can I achive this?

Thank you!

Edit; I mean something like;

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

I have ponent 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 
ponents) or a class/function (for posite ponents) but got: object.

How can I achive this?

Thank you!

Edit; I mean something like;

{children.map((Child,index)=> <Child {...newProps}/>)}
Share Improve this question edited Dec 25, 2017 at 18:07 Shubham Khatri 282k58 gold badges431 silver badges411 bronze badges asked Dec 24, 2017 at 6:57 MohamedMohamed 1,2713 gold badges15 silver badges37 bronze badges 1
  • assuming children is an array, you'll also potentially want to add a key property to each item - but I would check that all your ponents are exported properly out of their file they are defined in, and importing it in properly. I would want to see how you defined that as well. – Spencer Bigum Commented Dec 24, 2017 at 7:12
Add a ment  | 

1 Answer 1

Reset to default 10

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
                });
            })}
发布评论

评论列表(0)

  1. 暂无评论