React JSX 中的 forEach() 不输出任何 HTML [英] forEach() in React JSX does not output any HTML

查看:30
本文介绍了React JSX 中的 forEach() 不输出任何 HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过 React 输出一个对象:

I have a object that I want to output via React:

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

和我的反应组件(减少),是另一个组件

and my react component (cut down), is another component

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 中.

as you can see from the snippit above, i'm trying to insert an array of the component Answer by using the array Answers in props, it does itterate but is not outputted into HTML.

推荐答案

您需要将元素数组传递给 jsx.问题在于 forEach 不返回任何内容(即返回 undefined).所以最好使用 map 因为 map 返回一个数组:

You need to pass an array of element to jsx. The problem is that forEach does not return anything (i.e it returns undefined). So it's better to use map because map returns an array:

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;

这篇关于React JSX 中的 forEach() 不输出任何 HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆