简体   繁体   中英

How to loop thorough object and create child component in React.js

I am new to React.js and getting stuck loop thorough child component. I have an object and I need to loop through it which should create child component using the values of that object. Thank you in advance

var o = {
    playerA: {
        name: 'a',
    },

    playerB: {
        name: 'b',
    }
};


var Players = React.createClass({
    getPlayers: function(){
        return o;
    },    

    render: function() {
        return (
            <div>
                <div className="row"> Players</div>
                {this.getPlayers()}
                <Player /> 
            </div>
        );
    }
});


var Player = React.createClass({    
    render: function(){
        return (
            <div className="row" > player {this.name} < /div>
        )
    }
});

React.render(<Players />, document.getElementById('container'));

The result should be:

player a

player b


I have fiddle set up at: http://jsfiddle.net/rexonms/7f39Ljbj/

First, you'll iterate over the data with .map so that you can return markup (the child component) for each item. In the child component markup, you pass the data for that item in an attribute.

{Object.keys(yourObject).map(function(key) {
  return (
    // Add a key to the list item, it is mandatory from react
    // What the key consists of if it's the id or not is up to you
    // it needs to be unique though
    <ChildComponent key={key} data={yourObject[key]}/>
  );
})}

The child component's markup can then use that data by binding this.props.data .

<div>Player: {this.props.data.name}</div>

You don't have to use the name "data" for the attribute/property. Something like info={yourObject[key]} with this.prop.info is just as valid.

Working JS Fiddle here.

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