【问题标题】:Passing props to a component from nested array in React从 React 中的嵌套数组将道具传递给组件
【发布时间】:2021-12-07 21:16:53
【问题描述】:

我有一个嵌套数组,如下所示。手风琴应按编号显示。我拥有的数组和手风琴摘要将包含详细信息“标题”、“总价格”。而手风琴详细信息将包含“subcontents”、“Subtitle”和“SubtitlePrice”。

let summaryContents: any[] = [
{
  Title: "Construction costs",
  TotalPrice: "$25000",
  Subcontents: [
    {
      Subtitle: "Sanitation",
      SubtitlePrice: "$5000",
    },
    {
      Subtitle: "PoolLights",
      SubtitlePrice: "$5000",
    },
    {
      Subtitle: "PoolCleaner",
      SubtitlePrice: "$15000",
    },
  ],
},
{
  Title: "Pool interior costs",
  TotalPrice: "$20000",
  Subcontents: [
    {
      Subtitle: "Title1",
      SubtitlePrice: "$5000",
    },
    {
      Subtitle: "Title2",
      SubtitlePrice: "$10000",
    },
    {
      Subtitle: "Title3",
      SubtitlePrice: "$5000",
    },
  ],
}

我必须将这些值作为道具传递给另一个组件。如果它在我知道的组件内,我们可以做这样的事情

return (
<>
  {summaryContents.map((item: any) => {
    <>
      {item.Title}
      {item.TotalPrice}

      {typeof item.Subcontents == "object" ? (
        <>
          {item.Subcontents.map((subItem: any) => (
            <>
              {subItem.Subtitle}
              {subItem.SubtitlePrice}
              
            </>
          ))}
        </>
      ) : null}
</>;
  })}

</>


 );

我们可以做些什么来传递另一个像下面给出的组件

<QuoteSummary
  Title={item.Title}
  TotalPrice={item.TotalPrice}
  Subtitle={item.Subcontents.Subtitle}
  SubtitlePrice={item.Subcontents.SubtitlePrice}
/>

【问题讨论】:

    标签: reactjs typescript multidimensional-array foreach react-props


    【解决方案1】:

    嗯,这可能会对你有所帮助。

    // your parent component
      return (
        <>
          {summaryContents.map((item: any) => {
            return <QuoteSummary
              Title={item.Title}
              TotalPrice={item.TotalPrice}
              Subcontents={item.Subcontents}
            />
          })}
        </>
      );
    
    // Your child1 component
    const QuoteSummary = ({ Title, TotalPrice, Subcontents }) => {
      return (
        <>
          {Title}
          {TotalPrice}
          {Subcontents.map((item: any) => {
            return <SubContent
              Subtitle={item.Subtitle}
              SubtitlePrice={item.SubtitlePrice}
            />
          })}
        </>
      );
    }
    
    // Your child2 component 
    const SubContent = ({ Subtitle, SubtitlePrice }) => {
      return <>
        {Subtitle}
        {SubtitlePrice}
      </>
    }
    
    

    【讨论】:

    • 感谢您的回答,但在这里我不应该更改通过组件传递的道具,通过组件传递的道具应如下 Title TotalPrice Subtitle SubtitlePrice
    猜你喜欢
    • 2016-08-17
    • 1970-01-01
    • 2016-12-18
    • 1970-01-01
    • 2020-12-21
    • 2017-02-19
    • 1970-01-01
    • 2017-10-20
    • 2019-04-08
    相关资源
    最近更新 更多