简体   繁体   中英

Using React, what is the proper way to render an element with multiple nested elements?

Using React, how do I render a <div> with multiple nested <div> 's inside them? See code below.

var SubTrait = React.createClass({

  render: function() {
    var subTraits = this.props.data;
    return (
    <div className = "subTraitContainer">
      <div>
        { subTraits.forEach(function(subTrait) {
          return (
            <div>
              <h4>{ subTrait.name }</h4>,
              Sub-Sub-Traits
              <SubSubTrait data={ subTrait.children } />
            </div>
          );
        })}
      </div>
    </div>
    );
  }
});

The end result I get with this code is:

在此处输入图片说明

-edit- Would the proper way to do this be to create my nodes first using .forEach , then passing the created nodes to the render function's return ? (I'm looking at the React Tutorial at React Docs . Would my original solution be possible, or is the only way to pre-create the nodes before returning them?

You need to use map instead of forEach . forEach returns nothing, so the result is:

<div class="subTraitContainer">
  <div></div>
<div>

map returns an array. It maps each element in the given array to something new. For example, you could map an array of User s to their username s. If you use map instead of forEach , you will get an array of <div> s, which should do what you expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM