首页 > 解决方案 > 从 JSX 内部的渲染访问数组

问题描述

我正在尝试从返回内部的渲染中遍历返回的数组。

class Example extends React.Component {
  render() {
    let actortype = 1;
    const arr1 = ['a', 'b', 'c'];
    const arr2 = ['x', 'y', 'z'];
    if (actortype == 1) {
      var array = [...arr1]; //clone arr1 to array
    } else {
      var array = [...arr2];
    }
    return (
      <div>
           //I want to map through the array returned above in render. I am doing something like this:
                array.map((index)=>{
                <div>testing</div>      
            })
         // seems not the right approach to  access array inside return. returns plain text
      </div>
    );
  }
}

请分享您的反馈,我该怎么做。

标签: javascriptreactjs

解决方案


在 , 中使用 JSX 表达式 ( {})div来调用map

<div>
    {array.map( item => <div>{item}</div>})}
</div>

并使用return或使用简洁的箭头函数(我在上面完成了后者)。有关后一点的更多信息,请参阅为什么我的箭头函数不返回任何内容?


推荐阅读