当我从父级传播 .map()
的结果时,我有一些奇怪的行为,其中 this.props.children
正在转换为一个对象。
示例:
const items = [
{ id: 1, name: "Name1" },
{ id: 2, name: "Name2" }
].map((item) => {
return (
<DropdownMenu_listItem key={item.id} item={item} />
);
});
render() {
return (
<DropdownMenu
label={'Some label'}
onChange={() => {}}
>
{...items}
</DropdownMenu>
);
}
// DropdownMenu.js
render() {
console.log(this.props.children); // {0: {…}, 1: {…}}
return (
// ...
);
}
奇怪的是,当我省略 .map()
并直接传递元素时,它们像预期的那样作为数组出现在 this.props.children
中:
render() {
return (
<DropdownMenu
label={'Some label'}
onChange={() => {}}
>
<DropdownMenu_listItem item={{...}} />
<DropdownMenu_listItem item={{...}} />
</DropdownMenu>
);
}
// DropdownMenu.js
render() {
console.log(this.props.children); // [{…}, {…}]
return (
// ...
);
}
如果能深入了解为什么会发生这种情况,我们将不胜感激。
最佳答案
这不是因为 map 你得到 child 作为对象,而是因为你对
中的项目使用了展开运算符<DropdownMenu
label={'Some label'}
onChange={() => {}}
>
{...items} {/*spread operator here */}
</DropdownMenu>
既然 map items is an array using {...items }
使它成为一个对象,因为你用 {}
包装了展开运算符的结果,如果你编写{items}
,这样就可以了
<DropdownMenu
label={'Some label'}
onChange={() => {}}
>
{items}
</DropdownMenu>
关于javascript - React.js - this.props.children 一个对象,当从父级传播 .map 的结果时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49421890/