【问题标题】:Map and render two different arrays in the same component - React在同一个组件中映射和渲染两个不同的数组 - React
【发布时间】:2021-05-29 13:35:15
【问题描述】:

我刚开始学习 React,但在理解如何在同一个组件中映射和渲染两个不同的数组时遇到了问题。在我的 CMS 中,我有 3 个条目,每个条目都包含一个标题和一个描述。我使用 var data 从 GraphQL 调用它们。组件SectionLeft 有一个以threeFeatures 作为类名的网格容器。在我的主页中,我使用道具bottomcontent 将内容传递给网格容器。我在数组中传递组件SingleFeature,这是我的网格列,将包含一个图标、一个标题和一个描述,它将重复 3 次并组成我的 3 列 x 1 行网格。组件SingleFeature 具有属性children,它应该包含常量iconList 的数组映射,其中包含3 个不同的svg 图标组件。我不明白如何为组件SingleFeature 编写一个多数组映射,它将为道具featuredetails 显示下面显示的相同data 数组,但将为children 渲染3 个组件在数组中。任何解释将不胜感激。谢谢。

homepage.js

import IconOne from "../components/icons/icon-one"

import IconTwo from "../components/icons/icon-two"

import IconThree from "../components/icons/icon-three"

export const iconList = [IconOne, IconTwo, IconThree]

export default function Home({data}) {

  return (
    <div>
      <SectionLeft bottomcontent =

      {data.allContentfulHomepageWordpressFeatures.edges.map(edge => (

          <SingleFeature
          
          children = {
            ...iconList array...
          }
          feature = {
            edge.node.feature
          }
          details = {
            edge.node.description
          }
          />

        ))
      }
     />
   );
}

section-left.js

export default function SectionLeft(props) {

    return (
                <div className="threeFeatures">{props.bottomcontent}</div>

    );
}

single-feature.js

export default function SingleFeature(props) {
    return(
        <div>
        {props.children}
        <h3>{props.feature}</h3>
        <p>{props.details}</p>
        </div>
    );
}

GraphQL 查询

export const query = graphql`

  allContentfulHomepageSpeedFeatures {
    edges {
      node {
        feature
        description
      }
    }
  }

}

`

【问题讨论】:

  • homepage.js存在语法错误。
  • 在每个 impot 行之后使用 ; 因为你会得到另一个错误

标签: reactjs


【解决方案1】:

我会这样做:

data.allContentfulHomepageWordpressFeatures.edges.map((edge, index) => (

      <SingleFeature
      
      children = {
        iconList[index]
      }
      feature = {
        edge.node.feature
      }
      details = {
        edge.node.description
      }
      />

    ))

map 将映射数组中元素的索引作为第二个参数传递给箭头函数。

【讨论】:

  • 完美,完美,我只需要这样写常量: const iconList = [, , ]
  • 对!我忘记了您将图标作为组件直接传递给孩子。我没有集中映射部分。
猜你喜欢
  • 2021-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-29
  • 2020-02-05
  • 2019-04-12
  • 2019-12-23
  • 2017-04-17
相关资源
最近更新 更多