问题描述
一个非常简单的问题,当我使用 .map
函数渲染渲染组件时遍历数组时,说:
very simple question, when I loop through array when rendering react compnent with .map
function, say:
render() {
let board = this.props.board;
return (
<div>
{
board.map((piece,index) => {
return (
<Piece data={piece}/>
);
})
}
</div>
);
}
我正在尝试每5条添加一个换行符,所以(index%5 == 0)
在之前添加
< br/>
< Piece/>
当我尝试使用 +
进行修饰或执行类似操作时:
I'm trying to add a break line every 5 pieces so (index % 5 == 0)
add <br />
before the <Piece />
when I try to concatinate with +
or to do something like this:
board.map((piece,index) => {
return (
(index % 5 == 0) ? <br /> : ''
<Piece data={piece}/>
);
})
我正在得到 [Object object]
's
推荐答案
返回 [< br/> ;,< Piece>]
(如果条件成立),否则仅返回 Piece
组件.参见小提琴.
Return an array of [ <br />, <Piece> ]
if the condition holds and return just the Piece
component otherwise. See the fiddle.
相关的代码段是这样的:
The relevant piece of code is this:
return <div>{items.map(function (i, index) {
if (index % 5 === 0) {
return [ <br key={index + "break"} />, <Item key={index} num={i} /> ];
}
return <Item key={index} num={i} />;
})}</div>;
此外,将 key
放在从 map
返回的组件上或其他返回类数组实例的方式上.这样,React不需要取出所有生成的组件并在每个渲染器上替换它们,而只需在键下找到它们并更新其属性即可.请查看React文档中的对帐以了解更多信息.
Also, put key
on the components you return from map
or other ways that return array-like instances. This way, React doesn't need to take out all the generated components and replace them on each render, but can just find them under the key and update their attributes. Check out Reconciliation in React docs to learn more.
这篇关于使用ReactJS和concat JSX语法进行渲染时的map函数循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!