一个组件中的两组数据

时间:2016-09-15 17:42:53

标签: reactjs

我将数据传递给没有问题的组件 - 但是,我现在想重新使用具有不同数据集的组件:

import React from 'react';

const people = [{
    id: 1,
    name: "John",
    age: 32,
    hobby: "jogging",
  },{
    id: 2,
    name: "John",
    age: 32,
    hobby: "jogging",
}];

const cars = [{
    id: 1,
    manufacturer: "Ford",
    model: "Focus",
    year: "2014",
  },{
    id: 2,
    manufacturer: "Honda",
    model: "Civic",
    year: "2012",
}];

export default function ListGroup(props) {
  return (
    <div>
      {props.people.map((person) =>
        <li key={person.id}>
           <p>Name: {person.name}</p>
           <p>Hobby: {person.hobby}</p>
        </li>
      )}
    </div>
  );
}

上面的代码适用于people fixture,但是要使用相同的组件,我不确定最简单的路径是什么。欢迎任何指导。

1 个答案:

答案 0 :(得分:0)

使用Object.keys(component).map(function(attributes){}迭代id。我把它呈现为一个组件,你也可以像功能一样使用它。我希望你能把它转换成你想要的方式。

&#13;
&#13;
class ListGroup extends React.Component {
 constructor(props) {
     super(props);
 }
 render() {
  return (
    <div>
      {this.props.value.map((component) => {
       
       return (
        <li key={component.id}>
           {Object.keys(component).map(function(attributes) {
               
               return (
                <p>{attributes} : {component[attributes]}</p>
               )
           }, this)}
           
        </li>
        )
      })}
    </div>
  );
}


}

class Hello extends React.Component {
constructor() {
  super();
}

  
  render() {
    const people = [{
    id: 1,
    name: "John",
    age: 32,
    hobby: "jogging",
  },{
    id: 2,
    name: "John",
    age: 32,
    hobby: "jogging",
}];

const cars = [{
    id: 1,
    manufacturer: "Ford",
    model: "Focus",
    year: "2014",
  },{
    id: 2,
    manufacturer: "Honda",
    model: "Civic",
    year: "2012",
}];
      return (
        <div>
          <ListGroup value={people} />
          <ListGroup value={cars} />
        </div>
      )
  }
}

ReactDOM.render(<Hello /> ,document.getElementById('app'));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>
<div id="app"></div>
&#13;
&#13;
&#13;