How do i use for loops with react?

This question already has an answer here:

  • Loop inside React JSX 38 answers
  • How to loop and render elements in React.js without an array of objects to map? 5 answers
  • for loop in react 1 answer

  • 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.


    有了地图,你可以做到:

    Users.map((user, index) => (
      <MenuItem eventKey={index}>user.firstname</MenuItem>
    ));
    
    链接地址: http://www.djcxy.com/p/52042.html

    上一篇: 在JSX中使用For循环

    下一篇: 我如何使用循环与反应?