如何在 React 中映射嵌套数据对象?
How to map a nested data object in React?
如何进一步访问此对象数组中的“名称”和“描述”?例如,我的目标是呈现两个按钮,上面写着 Term 1 和 Term 2?我将有 3 张幻灯片,每张幻灯片都有不同的 terms/definitions。所以我考虑制作一个组件,我可以在其中通过引用要呈现的术语集的道具传递索引。因此每张幻灯片将显示一组不同的术语名称和定义。
const TermData = [
{
index: 1,
slideTitle: "Key Terms (1 of 3)",
terms: [
{
name: "Term 1",
definition: "Definition 1",
},
{
name: "Term 2 ",
definition: " definition 2",
},
],
},
{
index: 2,
slideTitle: "Key Terms (2 of 3)",
terms: [
{
name: "Term 1",
definition: "Definition 1",
},
{
name: "Term 2 ",
definition: " definition 2",
},
],
},
];
//MAP THROUGH THE DATA - RENDER THE BUTTONS WITH TERM1 and TERM2 TITLE//
const termSet = TermData.map((set, index) => {
return (
<>
<button className="terms-button" key={index} onClick={() => handleClick(index)}>
{set.terms[0].name}
</button>
</>
);
});
return (
<Fragment>
<div>
{termSet}
</div>
</Fragment>
);
您必须将以下方法更改为
//MAP THROUGH THE DATA - RENDER THE BUTTONS WITH TERM1 and TERM2 TITLE//
const termSet = TermData[0].terms.map((set, index) => {
return (
<>
<button className="terms-button" key={index}>
{set.name}
</button>
</>
);
});
如何进一步访问此对象数组中的“名称”和“描述”?例如,我的目标是呈现两个按钮,上面写着 Term 1 和 Term 2?我将有 3 张幻灯片,每张幻灯片都有不同的 terms/definitions。所以我考虑制作一个组件,我可以在其中通过引用要呈现的术语集的道具传递索引。因此每张幻灯片将显示一组不同的术语名称和定义。
const TermData = [
{
index: 1,
slideTitle: "Key Terms (1 of 3)",
terms: [
{
name: "Term 1",
definition: "Definition 1",
},
{
name: "Term 2 ",
definition: " definition 2",
},
],
},
{
index: 2,
slideTitle: "Key Terms (2 of 3)",
terms: [
{
name: "Term 1",
definition: "Definition 1",
},
{
name: "Term 2 ",
definition: " definition 2",
},
],
},
];
//MAP THROUGH THE DATA - RENDER THE BUTTONS WITH TERM1 and TERM2 TITLE//
const termSet = TermData.map((set, index) => {
return (
<>
<button className="terms-button" key={index} onClick={() => handleClick(index)}>
{set.terms[0].name}
</button>
</>
);
});
return (
<Fragment>
<div>
{termSet}
</div>
</Fragment>
);
您必须将以下方法更改为
//MAP THROUGH THE DATA - RENDER THE BUTTONS WITH TERM1 and TERM2 TITLE//
const termSet = TermData[0].terms.map((set, index) => {
return (
<>
<button className="terms-button" key={index}>
{set.name}
</button>
</>
);
});