我有一个我想通过 React 输出的对象:
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;
正如您从上面的代码片段中看到的那样,我正在尝试通过在 props 中使用数组 Answers 来插入组件 Answers 的数组,它会迭代但不会输出到 HTML 中。
您需要将一个元素数组传递给jsx. 问题是它 forEach 不返回任何东西(即它返回undefined)。所以最好使用map,因为map返回一个数组:
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={answer} answer={answer} />) })} } export default QuestionSet;