简体   繁体   English

如何根据 Reactjs 中的条件动态应用颜色?

[英]How to apply color dynamically based on condition in Reactjs?

 await REApiService.getCountryList().then((response: any) => {

    let countryList = response?.map((item: any) => {

      return {

        optionText: item.CountryName,

      };

    });

    setCountryData(countryList);

  });

Above is my country list API call, where it consists of many country names, followed by score for each of the country.以上是我的国家列表 API 调用,其中包含许多国家名称,后面是每个国家的分数。 and For each of the country, i want to apply the color based on the condition dynamically(using score).并且对于每个国家/地区,我想根据条件动态应用颜色(使用分数)。 For example, Below is my sample array.例如,下面是我的示例数组。 {"Code":"AF","Country":"Afghanistan", "Score":3 }, {“代码”:“AF”,“国家”:“阿富汗”, “得分”:3 },

Where if u look at the array,it has separate field called "Score" starting from "1,2,3,99" i want to apply color based on the score value.如果您查看数组,它有一个名为“Score”的单独字段,从“1,2,3,99”开始,我想根据得分值应用颜色。 like if score value is就像如果分值是

create an enum object with your color set (if you want specific values)使用您的颜色集创建一个枚举 object(如果您需要特定值)

const colors = {
  1: 'red',
  2: 'orange'
  //...
}

and in the component where you render the markup apply dynamic styling并在您呈现标记的组件中应用动态样式

<h4 style={{ color: colors[Score] }}>{ Country }</h4>

a more dynamic approach would be to manipulate an HSL (hue, saturation, lightness) value, a simple example would be一种更动态的方法是操纵 HSL(色调、饱和度、亮度)值,一个简单的例子是

<h4 style={{ color: `hsl(${ 360 / 100 * colors[Score], 100%, 50%)` }}>{ Country }</h4>

hue goes from red to red on a 360degree color span eg 0 = red, 120 = green, 240 = blue & 360 = red色调在 360 度颜色范围内从红色变为红色,例如 0 = 红色、120 = 绿色、240 = 蓝色和 360 = 红色

Is this helpful for you?这对您有帮助吗?

const colors = {
  "1": "red",
  "2": "orange",
  "3": "purple",
  "99": "dark red",
}

await REApiService.getCountryList().then((response: any) => {
  let countryList = response?.map((item: any) => {
    return {
      optionText: item.CountryName,
      value: item.Country_shortcode,
      color: colors[item.score],
    };
  });
  setCountryData(countryList);
});

Then you can use color in inline styling.然后您可以在内联样式中使用color

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM