[英]How to set the backgroundcolor with a function in react?
So basically I have a div and I need to apply 1 of 3 possible colors based on the value, from 0 to 29 the color is red, from 30 to 69 the color is yellow and for 70 to 100 the color is green, what I'm doing right now is creating a function that based on the value applies one style or another using an object, like this:所以基本上我有一个 div,我需要根据值应用 3 个可能的 colors 中的 1 个,从 0 到 29 颜色是红色,从 30 到 69 颜色是黄色,70 到 100 颜色是绿色,我我现在正在做的是创建一个 function,它基于值应用一种样式或另一种样式,使用 object,如下所示:
const useStyles = {
bar: {
low: {
backgroundColor: "#f44336"
},
...
}
}
const handleBackgroundColor = (valueInPercent: Number) => {
if (valueInPercent < 30) {
return useStyles.bar.low;
} else if (valueInPercent >= 30 && valueInPercent <= 70) {
return useStyles.bar.medium;
}
return useStyles.bar.high;
}
<div
style={
height: "75px", width: '75px',
backgroundColor: handleBackgroundColor(valueInPercent) }}
/>
But I get this error:但我收到此错误:
Type '{ backgroundColor: string;
输入 '{ backgroundColor: string; }' is not assignable to type 'BackgroundColor |
}' 不可分配给类型 'BackgroundColor | undefined'.
不明确的'。
Does someone knows how to fix this or is there a way to use a ternary operator for this?有人知道如何解决这个问题或者有没有办法为此使用三元运算符?
I solved it removing the object notation, and leave it like this:我解决了它删除 object 符号,并像这样保留它:
bar: {
low: "#f44336",
medium: "#efbb5aa3",
high: "#088208a3"
}
I solved it by changing the declaration of bar
to this:我通过将
bar
的声明更改为此来解决它:
bar: {
low: "#f44336",
medium: "#efbb5aa3",
high: "#088208a3"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.