繁体   English   中英

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

[英]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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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