map() 中的两次导入 div

Two imports div in map()

我正在考虑在 map() 中嵌入两个导入的可能性。 我的反应代码如下所示:

{this.state.dataExample.map(item => (                            
    <ItemsSection nameSection={item.name} />  

    item.data.map((post, index) => (

       <ItemsTasks
          key={index}
          title={post.name}
       />

    ))

))}

结果:

// from ItemsSection
<div className="items-section-name">
    <div className="section-name">{nameSection}</div>
</div>
// from ItemsTasks
<div className="item-data">
    <div className="item-title">{title}</div>
<div className="item-data">
    <div className="item-title">{title}</div>
</div>

这段代码应该说明我想要得到什么。尝试为每个 'element' 导入单独的 div。上面的代码报语法错误,但我不知道该怎么做。

你可以使用 React 的 Fragment

{
  this.state.dataExample.map(item => (
    <React.Fragment>
      <ItemsSection nameSection={item.name} />  
      {
        item.data.map((post, index) => (
           <ItemsTasks
              key={index}
              title={post.name}
           />
        ))
      }
    </React.Fragment>                       
  ))
}

来自docs,

A common pattern in React is for a component to return multiple elements. Fragments let you group a list of children without adding extra nodes to the DOM.

你可以使用片段,短语法<></>(它看起来像空标签),

{
  this.state.dataExample.map(item => (
    <>
      <ItemsSection nameSection={item.name} />  
      {
        item.data.map((post, index) => (
           <ItemsTasks
              key={index}
              title={post.name}
           />
        ))
      }
    </>                       
  ))
}

或者您可以从 react 包中导入 Fragment

import React, {Fragment} from 'react';


{
  this.state.dataExample.map(item => (
    <Fragment>
      <ItemsSection nameSection={item.name} />  
      {
        item.data.map((post, index) => (
           <ItemsTasks
              key={index}
              title={post.name}
           />
        ))
      }
    </Fragment>                       
  ))
}