ReactJS中如何动态更新CSS-in-JS类伪元素的background属性
React CSS-in-JS动态调整伪元素background属性实现方案
下面提供两种最常用的实现方式,你可以根据你项目用的CSS-in-JS库选择:
方案1:CSS变量实现(全库通用,兼容性好)
这是所有CSS-in-JS方案都通用的实现,不需要依赖特定库的API:
- 修改样式类定义,给伪元素的background属性绑定CSS变量,设置默认值为黑色:
goodOne: { position: 'relative', '&:before': { position: 'absolute', // 绑定自定义CSS变量,默认值为黑色 background: 'var(--good-one-bg, #000)', borderRadius: '50%', // 注意:伪元素必须设置content才会渲染,漏写的话可以加上 content: '""', // 可根据需求补充宽高、定位坐标 width: '12px', height: '12px', left: '-16px', top: '50%', transform: 'translateY(-50%)' } }
- 组件渲染时,根据场景动态给元素绑定CSS变量的值即可:
// 假设isRedScene是你判断是否需要红色背景的状态/变量 <div className={classes.goodOne} style={{ '--good-one-bg': isRedScene ? '#f00' : '#000' }} > Hello world </div>
方案2:样式传参实现(适配JSS/Emotion/Styled-components等支持动态传参的库)
如果你用的CSS-in-JS库支持样式接收动态参数(比如Material UI v4的makeStyles、Emotion的styled等),可以直接把判断逻辑放到样式定义里:
以JSS(Material UI v4)为例:
import { makeStyles } from '@material-ui/core/styles'; // 样式定义接收外部传入的props参数 const useStyles = makeStyles({ goodOne: (props) => ({ position: 'relative', '&:before': { position: 'absolute', background: props.isRedScene ? '#f00' : '#000', borderRadius: '50%', content: '""' } }) }); // 组件内使用 function YourComponent() { // 你的业务场景判断变量 const isRedScene = true; // 把变量传入样式钩子 const classes = useStyles({ isRedScene }); return <div className={classes.goodOne}>Hello world</div> }
注意:两种方案都需要确保伪元素设置了
content属性、宽高和定位坐标,否则伪元素不会正常渲染。
内容的提问来源于stack exchange,提问作者Lara
相关产品推荐
相关产品推荐

