2024-06-19 09:39AM
参考:https://stackoverflow.com/a/47616385/25407982
你需要将一个元素数组传递给JSX,问题是forEach不返回任何内容(即它返回undefined),所以最好使用map方法,因为map方法可以返回一个数组。
eg:
我想要通过React输出一个对象:
import React, { Component } from 'react';
const question = {
text: "Is this a good question?",
answers: [
"Yes",
"No",
"I don't know"
]
}
class Answer extends Component {
render() {
return (
<div>
{this.props.answer}
</div>
);
}
}
class QuestionSet extends Component {
render() {
return (
<div className="container">
<h1>{question.text}</h1>
{question.answers.forEach((answer, index) => (
<Answer key={index} answer={answer} />
))}
</div>
);
}
}
export default QuestionSet;
正如您从上面的代码片段中可以看到的,我尝试通过使用props中的数组Answers来插入组件Answer的数组,虽然它确实会迭代,但是不会输出到HTML中。
问题是 forEach
不返回任何内容(即它返回 undefined
) ,所以使用 map 方法:
import React, { Component } from 'react';
const question = {
text: "Is this a good question?",
answers: [
"Yes",
"No",
"I don't know"
]
}
class Answer extends Component {
render() {
return (
<div>
{this.props.answer}
</div>
);
}
}
class QuestionSet extends Component {
render() {
return (
<div className="container">
<h1>{question.text}</h1>
{question.answers.map((answer, index) => (
<Answer key={index} answer={answer} />
))}
</div>
);
}
}
export default QuestionSet;
登录
请登录后再发表评论。
评论列表:
目前还没有人发表评论