我正在使用 React 来显示新闻文章的 Material 设计网格列表。我将收到的 JSON 传递给此 GridList 组件 (this.props.newsArticles),并映射每个返回的结果,以便我可以根据数据是否具有高清图像来过滤数据,然后将数据发送到 MediaTile 进行渲染。我的 GridList 模块的 hasHiDefPictures 函数中的三元有问题。我收到语法错误。
const Components = {
MediaTile: React.createClass({
render: function() {
return (
<GridTile
title={this.props.tile.title}
>
<img src={this.props.tile.multimedia[0].url} />
</GridTile>
)
}
}),
GridList: React.createClass({
render: function() {
var newsArticles = this.props.newsArticles
var renderArticles = newsArticles.data.results.map(function(tile, key) {
return hasHiDefPictures(tile, key)
})
function hasHiDefPictures(tile, key) {
return {tile.multimedia > 3 ? <Components.MediaTile key={key} tile={tile}/> : ""}
};
return (
<div>
<GridList>
{renderArticles}
</GridList>
</div>
);
}
})
}
现在解决此语法错误的唯一方法是将返回值包装在 div 中,如下所示:
function hasHiDefPictures(tile, key) {
return (
<div>
{tile.multimedia > 3 ? <Components.MediaTile key={key} tile={tile}/> : ""}
</div>
)
};
但我不想那样做。有人对如何解决这个问题有建议吗?我对 react 还很陌生,所以很有可能我没有在正确的位置处理数据。任何帮助,将不胜感激!谢谢!
最佳答案
您只需删除三元组周围的 {} 即可。 {} 在 JSX(以 <
开头的表达式)中用于评估某些 JS 代码非常有用,但是您的数组映射已经出现在纯 JS 代码中(渲染函数的开头),因此它具有常规 JS 含义: block 或对象字面量。
关于javascript - 使用 ReactJS 的映射函数内的三元,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38163306/