[英]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);
});
以上是我的國家列表 API 調用,其中包含許多國家名稱,后面是每個國家的分數。 並且對於每個國家/地區,我想根據條件動態應用顏色(使用分數)。 例如,下面是我的示例數組。 {“代碼”:“AF”,“國家”:“阿富汗”, “得分”:3 },
如果您查看數組,它有一個名為“Score”的單獨字段,從“1,2,3,99”開始,我想根據得分值應用顏色。 就像如果分值是
使用您的顏色集創建一個枚舉 object(如果您需要特定值)
const colors = {
1: 'red',
2: 'orange'
//...
}
並在您呈現標記的組件中應用動態樣式
<h4 style={{ color: colors[Score] }}>{ Country }</h4>
一種更動態的方法是操縱 HSL(色調、飽和度、亮度)值,一個簡單的例子是
<h4 style={{ color: `hsl(${ 360 / 100 * colors[Score], 100%, 50%)` }}>{ Country }</h4>
色調在 360 度顏色范圍內從紅色變為紅色,例如 0 = 紅色、120 = 綠色、240 = 藍色和 360 = 紅色
這對您有幫助嗎?
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);
});
然后您可以在內聯樣式中使用color
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.