gpt4 book ai didi

javascript - React - 将数组映射到子组件

转载 作者:数据小太阳 更新时间:2023-10-29 04:14:19 25 4
gpt4 key购买 nike

我正在编写一个包含多个页面的网站。页面 ComponentA 有一个子组件,该子组件返回带有标题和段落的部分。

ComponentA 中的数组将数据作为 Prop 传递给 child 。在 child 内部, map 函数返回正确的段落。标题缺少什么,如何将 title1 传递给 paragraph1,将 title2 传递给 paragraph2 等等?

组件A:

import Child from "../components/child";

const ComponentA = () => {
<Layout>
<h1>Home Page</h1>
<Child title={info.title} text={info.text} />
</Layout>
}

const info = {
title: ["Title1", "Title2"],
text: ["Paragraph1", "Paragraph2"]
};

子组件:

const Child = ({ text, title }) => {
return (
<div>
{text.map(text => {
return (
<div>
<h3>{title}</h3>
<p>{text}</p>
</div>
);
})}
</div>
);
};

最佳答案

您的 info 对象不是可迭代列表 - 所以我会将它们转换成列表 {title, text} 如下:

const data = info.title.map((e,i) => {
return {title : e, text: info.text[i]}
})

现在我会将 map() 函数转移到 ComponentA 而不是 Child 因为这使得子组件更有意义.

请看下面的演示:

const info = {
title: ["Title1", "Title2"],
text: ["Paragraph1", "Paragraph2"]
};

const data = info.title.map((e,i) => {
return {title : e, text: info.text[i]}
})

const ComponentA = () => {
return (
<div>
<h1>Home Page</h1>
{ data.map(item => {
return (
<Child key={item.title} title={item.title} text={item.text} />
);
})
}
</div>
)
}

const Child = ({ text, title }) => {
return (
<div>
<h3>{title}</h3>
<p>{text}</p>
</div>
);
};

ReactDOM.render(
<ComponentA/>,
document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"/>

关于javascript - React - 将数组映射到子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55321253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com