在JSX中反应foreach

reactjs React.js

西里米亚

2020-03-13

我有一个要通过REACT输出的对象

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

而我的react组件(已减少)是另一个组件

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;

从上面的代码片段中可以看到,我正在尝试通过在props中使用数组Answers来插入组件Answer的数组,它确实令人陶醉,但没有输出到HTML中。

第1530篇《在JSX中反应foreach》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
十三番长 2020.03.13

您需要将元素数组传递给jsx问题是forEach什么都不返回(即返回undefined)。更好地使用,map因为它返回这样的数组

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;

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android