javascript - React.js - this.props.children 一个对象,当从父级传播 .map 的结果时

标签 javascript reactjs children

当我从父级传播 .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/

相关文章:

javascript - IndexedDB 和多对多关系

iphone - UIView 应该如何获取对其子级的引用?

java - 使用 axios 从 React js 调用 Spring Boot get 方法时,浏览器显示 "request has been blocked by CORS policy"

reactjs - 如何从 @react-native-firebase/auth 模拟身份验证

reactjs - 如何获取当前导航状态

C - 二叉树 : error while appending a new child to the tree

jQuery:.children()[index] 不允许函数调用

javascript - 如何在javascript中使模块异步

javascript - JQuery - 追加到已使用 Jquery 修改的文本区域

javascript - 尝试将 javascript 变量作为图像源