How to loop and render elements in React.js without an array of objects to map?

前端 未结 5 1681
轻奢々
轻奢々 2020-11-28 01:35

I\'m trying to convert a jQuery component to React.js and one of the things I\'m having difficulty with is rendering n number of elements based on a for loop.

I un

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-28 01:42

    Updated: As of React > 0.16

    Render method does not necessarily have to return a single element. An array can also be returned.

    var indents = [];
    for (var i = 0; i < this.props.level; i++) {
      indents.push();
    }
    return indents;
    

    OR

    return this.props.level.map((item, index) => (
        
            {index}
        
    ));
    

    Docs here explaining about JSX children


    OLD:

    You can use one loop instead

    var indents = [];
    for (var i = 0; i < this.props.level; i++) {
      indents.push();
    }
    return (
       
    {indents} "Some text value"
    );

    You can also use .map and fancy es6

    return (
       
    {this.props.level.map((item, index) => ( ))} "Some text value"
    );

    Also, you have to wrap the return value in a container. I used div in the above example

    As the docs say here

    Currently, in a component's render, you can only return one node; if you have, say, a list of divs to return, you must wrap your components within a div, span or any other component.

提交回复
热议问题