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

Cel*_*iel 8 javascript children reactjs

this.props.children当我.map()从父级传播 a 的结果时,我有一些奇怪的行为正在转换为对象。

例子:

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 (
    // ...
  );
}
Run Code Online (Sandbox Code Playgroud)

奇怪的是,当我省略.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 (
    // ...
  );
}
Run Code Online (Sandbox Code Playgroud)

任何有关为什么会发生这种情况的见解将不胜感激。

Shu*_*tri 7

不是因为地图将子项作为对象,而是因为您对中的项目使用了扩展运算符

<DropdownMenu
          label={'Some label'}
          onChange={() => {}}
        >
          {...items} {/*spread operator here */}
</DropdownMenu>
Run Code Online (Sandbox Code Playgroud)

现在,在 map items 之后是一个数组 using{...items }使其成为一个对象,因为您将扩展运算符的结果用 包装起来{},如果您编写{items},那会很好

 <DropdownMenu
      label={'Some label'}
      onChange={() => {}}
    >
      {items}
 </DropdownMenu>
Run Code Online (Sandbox Code Playgroud)

  • @SureshPonnukalai 在第二种情况下,他手动添加 `&lt;DropdownMenu_listItem item={{...}} /&gt; &lt;DropdownMenu_listItem item={{...}} /&gt;` 作为子项而不使用扩展运算符 (2认同)

RIY*_*HAN 7

{...items}被作为儿童传递DropdownMenu.js

它可作为this.props.children

this.props.children可以是数组或对象,具体取决于您渲染子元素的方式。

在你的情况下

<DropdownMenu
      label={'Some label'}
      onChange={() => {}}
    >
      {...items}
</DropdownMenu>
Run Code Online (Sandbox Code Playgroud)

items 是一个数组。据我们所知

array is also type of object in javascript

with key equal to element's index and value is element itself
Run Code Online (Sandbox Code Playgroud)

{...items}:这将作为一个对象传递,其中键作为元素索引,值等于数组元素。

要解决您的问题,您应该在不使用扩展运算符的情况下通过它。

{items}:这将作为数组传递。

<DropdownMenu
      label={'Some label'}
      onChange={() => {}}
    >
      {items}
</DropdownMenu>
Run Code Online (Sandbox Code Playgroud)