gpt4 book ai didi

javascript - React 组件中的三元条件 className

转载 作者:行者123 更新时间:2023-12-03 13:35:16 25 4
gpt4 key购买 nike

我从 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>
);
});

如果满足条件,此方法似乎只会将所有内容添加到类中,而不是“突出显示”类。

是否可以在 .map 方法中再次定义变量以减少重复?

我已经尝试过了var homeScore = {game.home.score}但是,运气不佳

最佳答案

您需要将整个三元语句放在括号中:

{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>
);
});

关于javascript - React 组件中的三元条件 className,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35421982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com