我想通过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;

正如您从上面的snippit中看到的,我试图通过使用props中的数组答案来插入一个组件答案数组,它不会被写入,但不会输出到HTML中.

推荐答案

需要将一个元素数组传递给jsx.问题是101 does not return anything (i.e it returns 102).所以最好使用map,因为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;

Reactjs相关问答推荐

CSS转换不适用于React MUI对象

使用useEffect挂钩获取数据

安装后未渲染tailwind

在Reaction中单击并显示子组件延迟/动画

Reaction路由DOM v6不包含上下文(Supabase)

REACTION-Easy-SORT返回.map错误

如何在中间件中获取 nextAuth 会话

在 React 中,为什么不将组件和钩子结合起来呢?

onClick 事件处理程序未应用于样式组件

在 Next13 中将 props 传递给 onClick 从服务器到客户端组件

当从子状态更改复制时,react 父状态更改.我该如何防止这种情况?

React useContext 的未定义返回值

使用jest如何覆盖对象的模拟?我正在使用`jest.mock()`来模拟对象,并希望 for each 测试用例覆盖模拟.

作为单个变量的 React 组件是否比 memoized 组件渲染得更快?

未捕获的类型错误:useSelector 不是函数

我应该使用 useEffect 来为 React Native Reanimated 的 prop 值变化设置动画吗?

渲染的钩子比预期的少.这可能是由 React Hooks 中意外的提前返回语句引起的

为什么重新渲染不会影响 setTimeout 的计数?

CORS 政策:无访问控制允许来源-AWS 和 Vercel

如何将本地视频文件上传到 Google Cloud