我如何在反应中使用 for 循环? [英] How do I use for loops with react?

查看:19
本文介绍了我如何在反应中使用 for 循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对反应很陌生,我真正想要的是一个简单的 for 循环,它为我的数组中的每个用户创建 menuitem 元素,其标题是他们的名字.所以这就是我要写的方式,但我不知道如何在反应中做到这一点.我认为它应该是一张地图,但我似乎无法让它工作,或者希望这里的任何人都可以帮助我.

for (var i = 0; i 

解决方案

组件的 render 方法或无状态组件函数返回要渲染的元素.

如果你想使用循环,那很好:

render() {让菜单项 = [];for (var i = 0; i 

更常见的是看到更多功能的样式,例如使用映射返回元素数组:

render() {返回 

{Users.map((user, i) =><MenuItem eventKey=[i]>User.firstname[i]</MenuItem>)}

;}

请注意,无论哪种情况,您都缺少数组中每个元素的 key 属性,因此您会看到警告.数组中的每个元素都应该有一个唯一的键,最好是某种形式的 ID 而不仅仅是数组索引.

I am 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>
}

解决方案

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>;
}

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.

这篇关于我如何在反应中使用 for 循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆