我想呈现新闻提要。文章可以有标题、图片和作者姓名。我这样渲染:
render() {
const newsItem = (article, id) => (
<article className="news-item" key={id}>
<img className="news-picture" src={`${article.urlToImage}`} alt=""/>
<h1 className="news-title">{article.title}</h1>
<p>Author: {article.author}</p>
</article>
);
const newsFeed = this.state.news.map(e => newsItem(e, pushid()));
return (
<div className="news-feed">{newsFeed}</div>
);
}
}
有时 API 不会提供作者姓名(值为空),如果是这样,我不想渲染
<p>Author: {article.author}</p>
在react中如何正确完成?
最佳答案
试试这个:
{article.author && <p>Author: {article.author}</p>}
这意味着如果 article.author
存在或不为空则渲染 <p>...</p>
.
这与 if
的情况相同。语句,只不过这里不能写 if 语句。这与那是相等的。
if(article.author) return <p>Author: {article.author}</p>
关于javascript - 如果元素为空,如何不渲染它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55708928/