为什么这个箭头函数中的 adding/removing 花括号导致 ReactJS 组件不显示文本?
Why does adding/removing curly braces in this arrow function cause the text to not display for a ReactJS component?
const tasks = [
{
id: 1,
text: 'Doctors Appointment',
day: "Feb 5th at 2:30 pm",
reminder: true,
},
{
id: 2,
text: "Meeting at School",
day: "Feb 6th at 1:30pm",
reminder: true,
},
{
id: 3,
text: "Food Shopping",
day: "Feb 5th at 2:30pm",
reminder: false,
},
];
const Tasks = () => {
return (
<>
{
tasks.map((task) =>
<h3>{task.text}</h3>
)
}
</>
)
}
export default Tasks;
这是我的组件。
最初我在箭头函数中有花括号,所以它看起来像这样:
tasks.map((task) => {
<h3>{task.text}</h3>
}
但是,这样做会使文本消失。所以我删除了这些花括号,突然出现了文字。
为什么添加花括号会破坏这个箭头函数?
谢谢!
您需要 return 关键字,以防您在箭头函数中使用大括号。
tasks.map((task) => {
return <h3>{task.text}</h3>
}
)
花括号用于分隔函数体,因此您需要 return
语句 return 一个值:
tasks.map((task) => {
return <h3>{task.text}</h3>
})
const tasks = [
{
id: 1,
text: 'Doctors Appointment',
day: "Feb 5th at 2:30 pm",
reminder: true,
},
{
id: 2,
text: "Meeting at School",
day: "Feb 6th at 1:30pm",
reminder: true,
},
{
id: 3,
text: "Food Shopping",
day: "Feb 5th at 2:30pm",
reminder: false,
},
];
const Tasks = () => {
return (
<>
{
tasks.map((task) =>
<h3>{task.text}</h3>
)
}
</>
)
}
export default Tasks;
这是我的组件。 最初我在箭头函数中有花括号,所以它看起来像这样:
tasks.map((task) => {
<h3>{task.text}</h3>
}
但是,这样做会使文本消失。所以我删除了这些花括号,突然出现了文字。
为什么添加花括号会破坏这个箭头函数?
谢谢!
您需要 return 关键字,以防您在箭头函数中使用大括号。
tasks.map((task) => {
return <h3>{task.text}</h3>
}
)
花括号用于分隔函数体,因此您需要 return
语句 return 一个值:
tasks.map((task) => {
return <h3>{task.text}</h3>
})