循环遍历数组并使用React使用该数据呈现子组件的多个实例?

时间:2017-04-21 06:03:10

标签: reactjs

我有一个名为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

1 个答案:

答案 0 :(得分:5)

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

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

此处您的反应组件也是内联无状态组件。它只是一个常规函数,没有反应this上下文。又名你没有this.propsthis.state。你有props。当您想要访问道具时,您只需键入props而不是this.props