我如何使用带有响应的循环? [英] How do i use for loops with react?
问题描述
我是一个非常新的响应者,我真正想要的是一个简单的for循环,该循环为我数组中的每个用户创建menuitem元素,其标题是他们的名字.所以这就是我要写的方式,但是我不知道如何做出反应.我认为应该在地图上,但我似乎无法使它正常工作,希望这里的任何人都可以帮助我.
I'm very new to react and all I really want is a simple for loop that creates menuitem elements for each user in my array with the title of it being their firstname. So this is how I would write it, but I have no clue of how to do this in react. I think it should be with a map maybe but I cant seem to get it to work either hopefully anyone out here can help me.
for (var i = 0; i < Users.length; i++) {
<MenuItem eventKey=[i]>User.firstname[i]</MenuItem>
}
推荐答案
组件的render
方法或无状态组件函数将返回要渲染的元素.
The render
method of your component, or your stateless component function, returns the elements to be rendered.
如果要使用循环,可以:
If you want to use a loop, that's fine:
render() {
let menuItems = [];
for (var i = 0; i < Users.length; i++) {
menuItems.push(<MenuItem eventKey=[i]>User.firstname[i]</MenuItem>);
}
return <div>{menuItems}</div>;
}
更常见的是看到一种更实用的样式,例如使用地图返回元素数组:
More common would be to see a more functional style, such as using a map to return the array of elements:
render() {
return <div>
{
Users.map((user, i) =>
<MenuItem eventKey=[i]>User.firstname[i]</MenuItem>)
}
</div>;
}
请注意,在任何一种情况下,数组的每个元素都缺少key
属性,因此您将看到警告.数组中的每个元素都应具有唯一键,最好是某种形式的ID,而不仅仅是数组索引.
Note that in either case, you are missing the key
property from each element of your array, so you will see warnings. Each element in an array should have a unique key, preferably some form of ID rather than just the array index.
这篇关于我如何使用带有响应的循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!