将道具从 React 中的嵌套数组传递给组件

Passing props to a component from nested array in React

我有一个如下所示的嵌套数组。手风琴应根据编号显示。我拥有的数组和手风琴摘要将包含详细信息 'Title' ,'TotalPrice'。而手风琴详细信息将包含 'subcontents'、'Subtitle' 和 'SubtitlePrice'。

let summaryContents: any[] = [
{
  Title: "Construction costs",
  TotalPrice: "000",
  Subcontents: [
    {
      Subtitle: "Sanitation",
      SubtitlePrice: "00",
    },
    {
      Subtitle: "PoolLights",
      SubtitlePrice: "00",
    },
    {
      Subtitle: "PoolCleaner",
      SubtitlePrice: "000",
    },
  ],
},
{
  Title: "Pool interior costs",
  TotalPrice: "000",
  Subcontents: [
    {
      Subtitle: "Title1",
      SubtitlePrice: "00",
    },
    {
      Subtitle: "Title2",
      SubtitlePrice: "000",
    },
    {
      Subtitle: "Title3",
      SubtitlePrice: "00",
    },
  ],
}

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

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}
/>

嗯,这可能对你有帮助。

// 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}
  </>
}