使用一组数据创建多个相似的组件

Creating multiple similar components with an array of data

我有一个 json 文件,其中包含一组代表人的数据。

我想每人做一个组件。我应该制作一个组件并在我的渲染函数中循环遍历我的数据,还是应该在我的 ReactDOM.render 函数外部循环并在每个循环中传递特定的数据?

我应该这样做吗:

var PersonBox = React.createClass({
  render: function() {
    var person = this.props.data.map(function(person, index) {
          return <div id="person" key={index}>
                 // person stuff here
                  </div>
        });
        return (
                <div>
                  {person}
                </div>
              );
  }

ReactDOM.render(<PersonBox data={mydata} />, document.getElementById('container'));

或者我应该这样做:

var PersonBox = React.createClass({
  render: function() {
        return (
                <div>
                  // person stuff
                </div>
              );
  }  

mydata.map(function(person, index) {
        ReactDOM.render(<PersonBox data={person} />, document.getElementById('container'));
}

你应该使用第一个变体。你可以将你的代码拆分成小的组件,例如你可以将你的代码拆分成两个组件,就像这样

var Person = React.createClass({
  render: function() {
    return <div>
      Name is <strong>{ this.props.name }</strong>
    </div>
  }
});

var PersonBox = React.createClass({
  render: function() {
    var people = this.props.data.map(function(person, index) {
      return <Person key={ index } name={ person.name } />  
    });

    return <div>{ people }</div>
  }
}); 

Example