You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何根据分数条件为国家列表动态设置颜色?

实现方案

首先,更新API数据处理逻辑,保留Score字段(后续需要用它判断颜色):

await REApiService.getCountryList().then((response: any) => {
  let countryList = response?.map((item: any) => {
    return {
      optionText: item.Country,
      score: item.Score,
      code: item.Code
    };
  });
  setCountryData(countryList);
});

接下来,写一个根据Score返回对应颜色的工具函数,用对象映射更简洁直观:

// 定义分数与颜色的映射关系,可根据需求调整
const scoreColorMap = {
  1: 'green',
  2: 'yellow',
  3: 'orange',
  99: 'red'
};

// 获取对应颜色的函数,默认返回黑色
const getCountryColor = (score) => scoreColorMap[score] || 'black';

最后,在渲染组件时,动态给每个国家项设置颜色样式:

示例1:下拉选择框(Option)

<select>
  {countryData?.map((country, idx) => (
    <option
      key={idx}
      style={{ color: getCountryColor(country.score) }}
      value={country.code}
    >
      {country.optionText}
    </option>
  ))}
</select>

示例2:列表项(Li)

<ul>
  {countryData?.map((country, idx) => (
    <li
      key={idx}
      style={{ color: getCountryColor(country.score), padding: '4px 0' }}
    >
      {country.optionText} - 评分:{country.score}
    </li>
  ))}
</ul>

如果使用TypeScript,建议添加类型约束避免类型错误:

interface Country {
  optionText: string;
  score: number;
  code: string;
}

// 初始化state时指定类型
const [countryData, setCountryData] = useState<Country[]>([]);

内容的提问来源于stack exchange,提问作者djohnt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 14:48:15