首页 > 解决方案 > 是否可以渲染组件数组?

问题描述

class Home extends React.Component { 
     render() {
        const array = [<Hello />,<Hello />,<Hello />]
        return {array.map((item) => {
            return item
        })}
     }
}

我已经得到了上面的代码以及如何渲染具有 React 组件的数组。有可能还是有其他方法可以解决此类问题?

标签: reactjs

解决方案


您应该将{...}return 后的包装替换为(...),或省略它。然而,正如各种评论所述,一个简单return array;的就足够了。以下代码应为您提供所需的结果。

class App extends React.Component {
  render() {
    const array = [
      <Hello name="John" />,
      <Hello name="Max" />,
      <Hello name="Alex" />
    ];

    return array;
  }
}

编辑: 请注意,以下表示法(直接返回一个数组)仅适用于 React 16,以前的版本需要用 a<div>或 a<span>元素包装(感谢@BrianGenisio 的提示)。

如需更多交互模式,请查看此沙盒


推荐阅读