gpt4 book ai didi

reactjs - 循环遍历数组并使用 React 的数据渲染子组件的多个实例?

转载 作者:行者123 更新时间:2023-12-03 14:04:24 24 4
gpt4 key购买 nike

我有一个名为 ListContainer 的父组件,其中包含一个名为 ListItem 的子组件。我需要为名为 nameArray 的数组中的每个项目调用 ListItem,并从该数组中的值填充 ListItem 的名称。

export const ListItem = (props) => {
return <h2>Name: { props.name }</h2>;
};

export const ListContainer = (props) => {
const nameArray = [
{
name: "john",
age: "29"
},
{
name: "james",
age: "21"
}
];
return (
<div>
{ this.nameArray.map(function(item) {
return (
<ListItem name={ item.name } />
)
}) }
</div>
);
};

通过查看文档,我认为我需要使用 map 函数,但我对它在 JSX 中的工作原理感到困惑。

https://facebook.github.io/react/docs/lists-and-keys.html

最佳答案

您正在尝试引用渲染函数中创建的局部变量,因此请从 this.nameArray.map 中删除 this

{ nameArray.map( (item, i) => <ListItem key={i} name={ item.name } /> )}

这里的 react 组件也是一个内联无状态组件。它只是一个没有反应 this 上下文的常规函数​​。也就是说,您没有 this.propsthis.state。你只有props。当你想访问 props 时,你只需输入 props 而不是 this.props

关于reactjs - 循环遍历数组并使用 React 的数据渲染子组件的多个实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43535041/

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