我试图在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的新手,我不确定如何实现上述目标(多次添加组件)。
当前回答
您需要向数组中添加元素并渲染元素数组。这有助于减少重新渲染组件所需的时间。
下面是一些可能有用的粗略代码:
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>])
})
}
}
其他回答
只需执行以下操作:
<tbody>{new Array(numRows).fill(“”,0,numRows”).map((p,i)=><YourRaw key={i}/>)}</tbody>
render() {
const elements = ['one', 'two', 'three'];
const items = []
for (const [index, value] of elements.entries()) {
items.push(<li key={index}>{value}</li>)
}
return (
<div>
{items}
</div>
)
}
一行(假设numrows是一个数字):
<tbody>
{
Array(numrows).fill().map(function (v, i) {
return <ObjectRow/>
})
}
</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>])
})
}
}
要循环多次并返回,可以通过from和map实现:
<tbody>
{
Array.from(Array(i)).map(() => <ObjectRow />)
}
</tbody>
其中i=次数
如果您想为渲染组件分配唯一的键ID,可以使用React文档中建议的React.Children.toArray
对阵列进行反应
将子级不透明数据结构作为平面数组返回,并为每个子级分配键。如果要在渲染方法中处理子对象的集合,特别是如果要在传递之前对this.props.children进行重新排序或切片,则非常有用。
注:React.Children.toArray()在展平子列表时更改键以保留嵌套数组的语义。也就是说,toArray在返回的数组中给每个键加前缀,以便每个元素的键都被限定到包含它的输入数组中。
<tbody>
{
React.Children.toArray(
Array.from(Array(i)).map(() => <ObjectRow />)
)
}
</tbody>