reactjs - 是否可以渲染组件数组?
问题描述
class Home extends React.Component {
render() {
const array = [<Hello />,<Hello />,<Hello />]
return {array.map((item) => {
return item
})}
}
}
我已经得到了上面的代码以及如何渲染具有 React 组件的数组。有可能还是有其他方法可以解决此类问题?
解决方案
您应该将{...}
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 的提示)。
如需更多交互模式,请查看此沙盒
推荐阅读
- c# - C# - ListView 总是显示重复项
- java - 按多列中的值对二维数组进行排序
- express - 错误:getaddrinfo EAI_AGAIN 未定义(ldapjs)
- python - 如何不部署在 git 控制的 db.sqlite3 文件下
- gpu - 现代 GPU 可以同时运行多个内核吗?
- html - Bootstrap 4:对新块使用“.row”还是“.col-12”更好?为什么?
- python - 在 Numpy 数组中提取小数点后的数字
- c# - 如果输入“x”文本,是否可以跳过下一行?C#
- apache-spark - google Spark-BigQuery-Connector 如何利用 BigQuery Storage API?
- r - 如何使用 grep 功能进行搜索?