"反应js"如何使用道具传递数组数据?

时间:2018-01-26 00:55:54

标签: reactjs react-props

render() {
   const Array = this.props.students.map((data) => {
      return (
         <button 
           key={data.name}
           //key={data.birthDate}
           //key={data.age}
           //key={data.class}
         >{data.name}</button>
      );
   });

   return (
     <div>
       {Array}
       <StudentInfo name = {"Amira"}/>
     </div> 
   );
}

这是我的代码。目前,我尝试将<button></button>中的数组数据传递到<StudentInfo />并替换name = {"Amira"} 任何人都可以帮我这个吗?

谢谢。

3 个答案:

答案 0 :(得分:1)

这可能是您的答案:How to pass an array of items in REACT.js

答案 1 :(得分:1)

这样做可以解决问题,

render() {
   const nameArray = [];
   const Array = this.props.students.map((data) => {
      nameArray.push(data.name); //fill the array with names
      return (
         <button 
           key={data.name}
           //key={data.birthDate}
           //key={data.age}
           //key={data.class}
         >{data.name}</button>
      );
   });

   return (
     <div>
       {Array}
       <StudentInfo name = {nameArray}/>
     </div> 
   );
}

答案 2 :(得分:0)

你想做的是这样的事情

constructor(props){
  super(props);
  this.students = [
    {name: 'john'},
    {name: 'paul'},
    {name: 'clara'}
  ];      
  this.state = {
    selectedStudent: this.students[0]
  }
  this.selectStudent = this.selectStudent.bind(this);
}

selectStudent(student){
  this.setState({selectedStudent: student});
}

render(){
  return (
    <div>
      {this.students.map((student, i) => (
        <button key={i}
          onClick={() => this.selectStudent(student)}
        >{student.name}</button>
      ))}
      <h1>{this.state.selectedStudent.name}</h1>
    </div>
  );
}

在线演示:https://codesandbox.io/s/91wp5j33pw