首页 > 解决方案 > 按钮的背景颜色没有在 React 中立即更新,其他 css 属性工作正常

问题描述

我正在使用 React 和 Material-UI。为了过滤我使用过滤器和映射的数据。当我单击按钮时,其他 css 属性工作正常,但为什么我的背景颜色没有立即更新。如果我在按钮单击后单击外部区域一次,它会更新。

这是我的代码片段:

   const years = [2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019,2020];
   const Cards=()=>{
   const [activeYear, setActiveYear] = useState(null);
   const handleYear= (e,yr)=>{
         if(activeYear==yr)
            setActiveYear(null);
         else
           setActiveYear(yr);
    };

    return(
    .....
     // filter button
      {years.map((yr,index)=>(
                    <Grid item xs={12} sm={4} lg={6} style={{padding:'8px'}}>
                        <Chip 
                            key={index}
                            label={yr}
                            onClick={e=> handleYear(e,yr)}
                            className={activeYear==years[index]?classes.activeYear:''}
                        />
                    </Grid>
                    )  
        )}
        ......
       }

这是沙箱链接https://codesandbox.io/s/filter-using-tag-e65yy?file=/src/Cards.js

这就是它的工作方式

标签: cssreactjsbutton

解决方案


当我按照@m4n0 的建议向 css 文件添加背景颜色以覆盖默认悬停样式时,问题得到了解决

.MuiGrid-item .makeStyles-activeYear-8.MuiChip-clickable:hover,
.MuiGrid-item .makeStyles-activeYear-8.MuiChip-clickable:focus {
  background: #cfd;
}

推荐阅读