JSX 中的循环会生成一个包含数组的 child 元素。我要多个children
Looping in JSX produces a single child element containing an array. I want multiple children
我有一个名为 <Accordian>
的组件。使用它看起来像这样
<Accordian>
<AccordianSection label=“section1”>
<div> some content <div>
</AccordianSection>
<AccordianSection label=“section2”>
<div> some other <div>
</AccordianSection>
</Accordian>
效果很好。当我使用 JSX 映射迭代创建部分时,我 运行 遇到了问题:
<Accordian>
<AccordianSection label=“section1”>
<div> some content <div>
</AccordianSection>
{ props.sections.map( section =>
<AccordianSection label=“section.label”>
<div> section.contents <div>
</AccordianSection>
)}
<AccordianSection label=“section2”>
<div> some other <div>
</AccordianSection>
</Accordian>
问题是 Accordion 代码期望它的 children 是一个 AccordianSection
的列表。但是上面Accordian
的children看起来像[AccordianSection, Array<AccordianSection>, AccordianSection]
。我基本上想要 "spread" 地图生成的元素,以便 Accordian
的 children 是 AccordianSections
的平面列表。有任何想法吗?
这是不可能的,但是您可以通过在 children
数组上使用 Array.prototype.flat
来更改 Accordion
中的逻辑。它将展平数组:
const children = [1, 2, [3, 4], 5];
console.log(children.flat());
试试这个
const renderAccordianSection = () => {
return [
<AccordianSection key="section1" label=“section1”>
<div> some content <div>
</AccordianSection>,
...props.sections.map(section =>
<AccordianSection key="section.label" label=“section.label”>
<div> section.contents <div>
</AccordianSection>
),
<AccordianSection key="section2" label=“section2”>
<div> some other <div>
</AccordianSection>
]
}
<Accordian>
{renderAccordianSection ()}
</Accordian>
我有一个名为 <Accordian>
的组件。使用它看起来像这样
<Accordian>
<AccordianSection label=“section1”>
<div> some content <div>
</AccordianSection>
<AccordianSection label=“section2”>
<div> some other <div>
</AccordianSection>
</Accordian>
效果很好。当我使用 JSX 映射迭代创建部分时,我 运行 遇到了问题:
<Accordian>
<AccordianSection label=“section1”>
<div> some content <div>
</AccordianSection>
{ props.sections.map( section =>
<AccordianSection label=“section.label”>
<div> section.contents <div>
</AccordianSection>
)}
<AccordianSection label=“section2”>
<div> some other <div>
</AccordianSection>
</Accordian>
问题是 Accordion 代码期望它的 children 是一个 AccordianSection
的列表。但是上面Accordian
的children看起来像[AccordianSection, Array<AccordianSection>, AccordianSection]
。我基本上想要 "spread" 地图生成的元素,以便 Accordian
的 children 是 AccordianSections
的平面列表。有任何想法吗?
这是不可能的,但是您可以通过在 children
数组上使用 Array.prototype.flat
来更改 Accordion
中的逻辑。它将展平数组:
const children = [1, 2, [3, 4], 5];
console.log(children.flat());
试试这个
const renderAccordianSection = () => {
return [
<AccordianSection key="section1" label=“section1”>
<div> some content <div>
</AccordianSection>,
...props.sections.map(section =>
<AccordianSection key="section.label" label=“section.label”>
<div> section.contents <div>
</AccordianSection>
),
<AccordianSection key="section2" label=“section2”>
<div> some other <div>
</AccordianSection>
]
}
<Accordian>
{renderAccordianSection ()}
</Accordian>