我试图在React JSX(其中ObjectRow是一个单独的组件)中执行以下操作:
<tbody>
for (var i=0; i < numrows; i++) {
<ObjectRow/>
}
</tbody>
我意识到并理解为什么这不是有效的JSX,因为JSX映射到函数调用。然而,由于来自模板领域,而且是JSX的新手,我不确定如何实现上述目标(多次添加组件)。
我试图在React JSX(其中ObjectRow是一个单独的组件)中执行以下操作:
<tbody>
for (var i=0; i < numrows; i++) {
<ObjectRow/>
}
</tbody>
我意识到并理解为什么这不是有效的JSX,因为JSX映射到函数调用。然而,由于来自模板领域,而且是JSX的新手,我不确定如何实现上述目标(多次添加组件)。
当前回答
Array.from是最好的方法。如果您想创建一个具有一定长度的JSX数组。
function App() {
return (
<tbody>
{Array.from({ length: 10 }, (_, key) => (
<ObjectRow {...{ key }} />
))}
</tbody>
);
}
上面的示例适用于没有数组的情况,因此,如果您有数组,则应在JSX中将其映射为:
function App() {
return (
<tbody>
{list.map((item, key) => (
<ObjectRow {...{ key }} />
))}
</tbody>
);
}
其他回答
只需使用.map()循环遍历集合,并从每个迭代返回带有道具的<ObjectRow>项。
假设对象是某处的数组。。。
<tbody>
{ objects.map((obj, index) => <ObjectRow obj={ obj } key={ index }/> ) }
</tbody>
您需要向数组中添加元素并渲染元素数组。这有助于减少重新渲染组件所需的时间。
下面是一些可能有用的粗略代码:
MyClass extends Component {
constructor() {
super(props)
this.state = { elements: [] }
}
render() {
return (<tbody>{this.state.elements}<tbody>)
}
add() {
/*
* The line below is a cheap way of adding to an array in the state.
* 1) Add <tr> to this.state.elements
* 2) Trigger a lifecycle update.
*/
this.setState({
elements: this.state.elements.concat([<tr key={elements.length}><td>Element</td></tr>])
})
}
}
如果您已经在使用lodash,_.times函数很方便。
import React, { Component } from "react";
import Select from "./Select";
import _ from "lodash";
export default class App extends Component {
render() {
return (
<div className="container">
<ol>
{_.times(3, (i) => (
<li key={i}>repeated 3 times</li>
))}
</ol>
</div>
);
}
}
好了,给你。
{
[1, 2, 3, 4, 5, 6].map((value, index) => {
return <div key={index}>{value}</div>
})
}
您所要做的只是映射数组并返回任何要渲染的内容。请不要忘记在返回的元素中使用key。
JSX内部的循环非常简单。试试看:
return this.state.data.map((item, index) => (
<ComponentName key={index} data={item} />
));