簡體   English   中英

如何使用 javascript 根據其值更改數字的顏色並做出反應?

[英]How to change color for the numbers based on its value using javascript and react?

我想使用 javascript 根據其值將 colors 應用於變量計數。

我想做什么? 變量 count 的值是動態的,它可以具有小於 0 或大於 0 的值。

所以現在當計數值為

0 color should be red
1 color should be yellow
greater than 1 color should be green
less than 0 meaning negative integers like -1, -2 so on color should be grey

我有下面的代碼,它根據值改變顏色。

const countColor = (count: number) => {
    const colors = [red, yellow];
    return colors[count] || green;
}; 

因此,上面的代碼適用於計數值為 0、1 和大於 1 的值。我如何更改上面的代碼,以便在值小於 0 時處理或將計數值更改為灰色

有人可以幫我解決這個問題。 謝謝。

一個簡單的方法是忘記[red, yellow]數組,只處理 count 以返回顏色:

const countColor = (count: number) => {
    if (count < 0) return grey;
    else if (count > 1) return green;
    else if (count === 0) return red;
    else if (count === 1) return yellow;
}; 

使用三元運算符,如果count小於零則返回grey ,否則返回colors[count]或如果colors[count] undefined則返回green

const countColor = (count: number) => {
    const colors = ['red', 'yellow'];
    return count < 0 ? 'grey' : (colors[count] || 'green');
}; 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM