2017-12-03 134 views
0

我有我想要输出对象通过REACT阵营的foreach在JSX

question = { 
    text: "Is this a good question?", 
    answers: [ 
     "Yes", 
     "No", 
     "I don't know" 
    ] 
} 

和我的反应成分(砍伐),是另一个组件

class QuestionSet extends Component { 
render(){ 
    <div className="container"> 
     <h1>{this.props.question.text}</h1> 
     {this.props.question.answers.forEach(answer => {  
      console.log("Entered"); //This does ifre      
      <Answer answer={answer} /> //THIS DOES NOT WORK 
     })} 
} 

export default QuestionSet; 

,你可以从看以上SNIPPIT,我试图通过使用阵列的答案中的道具插入组件回答的阵列,但它确实itterate但不被输出到HTML。

回答

0

你需要传递元素的数组jsxforEach不会返回任何内容。因此,使用地图,返回数组这样

class QuestionSet extends Component { 
render(){ 
    <div className="container"> 
     <h1>{this.props.question.text}</h1> 
     {this.props.question.answers.map((answer, i) => {  
      console.log("Entered");     
      // Return the element. Also pass key  
      return (<Answer key={i} answer={answer} />) 
     })} 
} 

export default QuestionSet;