我从json文件中提取数据并尝试仅在满足特定条件时添加类:
render: function() {
var gameList = this.props.data.map(function(game) {
return (
<li key={game.id} className="list-group-item">
{game.home_team_name}
<span className="pull-right {game.home.score} > {game.away.score} ? 'highlight':'' ">{game.home.score}</span> <br />
{game.away_team_name}
<span className="pull-right {game.home.score} > {game.away.score} ? 'highlight':'' ">{game.away.score}</span> <br />
{game.status.status}
</li>
);
});
这个方法似乎只是添加了类中的任何内容而不是“highlight”类,如果满足条件的话。
还可以在.map方法中再次定义变量以减少重复吗?
我试过了
var homeScore = {game.home.score}
但是,没有运气
答案 0 :(得分:7)
您需要将整个三元语句放在括号中:
{parseInt(game.home.score, 10) > parseInt(game.away.score, 10) ? 'highlight':''}
是的,您可以定义另一个变量。只需将其放在return
之前:
render: function() {
var gameList = this.props.data.map(function(game) {
var classNameExt = parseInt(game.home.score, 10) > parseInt(game.away.score, 10) ? 'highlight':'';
return (
<li key={game.id} className="list-group-item">
{game.home_team_name}
<span className={'pull-right ' + classNameExt}>{game.home.score}</span> <br />
{game.away_team_name}
<span className={'pull-right ' + classNameExt}>{game.away.score}</span> <br />
{game.status.status}
</li>
);
});
或者只突出胜利者:
render: function() {
var gameList = this.props.data.map(function(game) {
return (
<li key={game.id} className="list-group-item">
{game.home_team_name}
<span className={'pull-right ' + (parseInt(game.home.score, 10) > parseInt(game.away.score, 10) ? 'highlight':'')}>{game.home.score}</span> <br />
{game.away_team_name}
<span className={'pull-right ' + (parseInt(game.home.score, 10) < parseInt(game.away.score, 10) ? 'highlight':'')}>{game.away.score}</span> <br />
{game.status.status}
</li>
);
});