reactjs - Material-UI : Rating Component, 根据值改变颜色

标签 reactjs typescript material-ui material-design gatsby

目标
根据悬停期间的值更改评级(一个 material-ui 组件)的颜色。例如,如果我悬停在第 1 颗星上,则颜色变为红色,如果悬停在第 5 颗星上,则变为绿色。
enter image description here
我试过制作一个在悬停时改变颜色的自定义组件,就像这样 -

const StyledRating = withStyles({
  root: {
    color: "#ff6d75",
  },
  iconFilled: {
    color: '#ff6d75',
  },
  iconHover: {
    color: '#fff',
    backgroundColor: "#000",
  },
})(Rating);  
但它改变了所有图标的颜色。
任何人都可以指导我如何根据我选择或悬停的值更改评级颜色中的特定图标。
Current sandbox link .

最佳答案

您可以使用动态样式( Overriding styles with classes )

const useStyles = makeStyles({
  root: {
    // ...
  },
  'icon-1': { color: 'red' },
  'icon-2': { color: 'coral' },
  'icon-3': { color: 'orange' },
  'icon-4': { color: 'skyblue' },
  'icon-5': { color: 'green' }
});

export default function HoverRating() {
  // ... 
  return (
    <div className={classes.root}>
      <Rating
        classes={{
          iconHover: classes[`icon-${Math.ceil(hover)}`]
        }}
        //...
      />
      ...
    </div>
  );
}
Edit Material demo (forked)

关于reactjs - Material-UI : Rating Component, 根据值改变颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63451658/

相关文章:

javascript - 在 React 组件中渲染命名的 child ?

typescript - 元素隐式具有 'any' 类型,因为类型 'string' 的表达式不能用于索引

javascript - 将 Stackblitz HelloComponent 转变为 Web 组件?

reactjs - 将函数传递给包装的组件 Prop 时发出警告

javascript - Button 的悬停过渡效果

javascript - 当发布到数据库时,我收到 "Can' t set headers after they are sent error”

javascript - redux reducer 的多个键

javascript - Reactjs 和服务器上的数据

typescript - 错误 TS2322 : Type '{ id: string; }' is not assignable to type 'ApiModelFilter<M>'

javascript - 修改嵌套对象中的值