使用数据数组创建多个类似组件

Creating multiple similar components with an array of data

本文关键字:组件 创建 数据 数组      更新时间:2023-09-26

我有一个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