HTML 循环内不在 React 中呈现
HTML Within Loop Not Rendering in React
我正在尝试使用 Gatsby 在 DOM 中列出查询的帖子。下面的小片段应该足够了,因为 Graphql 查询正在正确获取数据。此代码段位于组件内,该组件也可以正确呈现。我是 Gatsby 和 React 的新手,希望我遗漏了一些非常基本的东西。
<div className="container">
Hello! // Renders
{newsItems.map(newsItem => {
console.log(newsItem.context.id); // Logs each news item id to console correctly
Hello! // Does not render
<p>{newsItem.context.id}</p> // Does not render
})}
</div>
您已经使用了花括号,所以这就是您 return 映射函数中的组件的方式。
{newsItems.map(newsItem => {
console.log(newsItem.context.id); // Logs each news item id to console correctly
return (
<>
Hello!
<p>{newsItem.context.id}</p>
</>
)
})}
还没有尝试过,但应该可以。这也仅在 newsItems
包含值时有效。使用 React Fragments <>...</>
是因为 return 必须只有 return 单个组件。您也可以使用 <div>...</div>
而不是 fragment.
试试这个。
我正在尝试使用 Gatsby 在 DOM 中列出查询的帖子。下面的小片段应该足够了,因为 Graphql 查询正在正确获取数据。此代码段位于组件内,该组件也可以正确呈现。我是 Gatsby 和 React 的新手,希望我遗漏了一些非常基本的东西。
<div className="container">
Hello! // Renders
{newsItems.map(newsItem => {
console.log(newsItem.context.id); // Logs each news item id to console correctly
Hello! // Does not render
<p>{newsItem.context.id}</p> // Does not render
})}
</div>
您已经使用了花括号,所以这就是您 return 映射函数中的组件的方式。
{newsItems.map(newsItem => {
console.log(newsItem.context.id); // Logs each news item id to console correctly
return (
<>
Hello!
<p>{newsItem.context.id}</p>
</>
)
})}
还没有尝试过,但应该可以。这也仅在 newsItems
包含值时有效。使用 React Fragments <>...</>
是因为 return 必须只有 return 单个组件。您也可以使用 <div>...</div>
而不是 fragment.
试试这个。