【发布时间】:2021-12-07 18:13:22
【问题描述】:
在这里,我试图通过将道具传递给组件的列表数组来呈现Accordion 的内容。我有点理解问题出在哪里,但我不知道我还能如何调用组件并传递道具。下面是我的代码。
父组件代码
const Sandbox = () => {
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",
},
],
},
];
let summaryContentsList: any[] = [];
summaryContents.forEach((item: any, index: number) => {
summaryContentsList.push(
<QuoteSummary
Title={item.Title}
TotalPrice={item.TotalPrice}
Subtitle={item.Subcontents.Subtitle}
SubtitlePrice={item.Subcontents.SubtitlePrice}
/>
);
});
return (
<>
{summaryContentsList}
</>
);
};
子组件的代码
const QuoteSummary: FC<QuoteSummaryProps> = (props: QuoteSummaryProps) => {
const classes = useStyles();
return (
<QuoteCard>
<Typography variant="h1" sx={{ paddingBottom: 2 }}>
Quote Summary
</Typography>
<DialogCloseButton onClose={clicked} />
<Accordion
className={classes.accordion}
sx={{
paddingTop: 0,
}}
>
<AccordionSummary
expandIcon={<ExpandMoreIcon />}
aria-controls="panel1a-content"
id="panel1a-header"
>
<Typography variant="h3">{props.Title}</Typography>
<Typography variant="h3" sx={{ paddingLeft: 10 }}>
{props.TotalPrice}
</Typography>
</AccordionSummary>
<AccordionDetails>
<Typography>{props.Subtitle}</Typography>
<Typography>{props.SubtitlePrice}</Typography>
</AccordionDetails>
</Accordion>
</QuoteCard>
);
};
这就是它的外观,因为我只想渲染一次标题和下面的手风琴内容。 我必须遵循的方法是什么
【问题讨论】:
-
逻辑是存在的,但问题是我通过一个组件渲染它,所以我将父组件的道具传递给子组件。所以你提供的链接不能解决它@wowandy
-
@kevinTHEprogrammer 我不明白你的要求。你想让标题
Quote Summary只出现一次吗?那你为什么不把它放在外面呢? -
@NearHuscarl 我在父组件
中渲染 组件。报价摘要标题位于 组件内。不知道在传递整个 组件时我应该如何将其从循环中取出。
标签: reactjs typescript foreach material-ui accordion