简体   繁体   中英

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:

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; }' is not assignable to type '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:

bar: {
    low: "#f44336",
    medium: "#efbb5aa3",
    high: "#088208a3"
}

I solved it by changing the declaration of bar to this:

bar: {
    low: "#f44336",
    medium: "#efbb5aa3",
    high: "#088208a3"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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