如何引用SCSS中的嵌套类并在CSS Module中正确调用组合样式
问题原因
你当前SCSS代码中.singleNews__image下的&.featured,编译后生成的选择器为.singleNews__image.featured,代表两个独立类名同时作用于同一元素时生效,不属于嵌套的BEM元素层级,也不是__image的内置后缀。
错误写法说明
你尝试的三种写法错误原因分别为:
styles.singleNews__image__featured:SCSS中没有定义singleNews__image__featured这个类,自然取不到对应值styles.singleNews__image featured:featured没有从styles对象中读取,是原生字符串类名,和CSS Module编译后带哈希后缀的实际类名不匹配styles.singleNews__image.featured:属于JS语法错误,不能直接在对象属性访问链中加.表示类名组合
正确写法
写法1:模板字符串拼接(最简便)
直接把两个类名从styles中取出,用空格拼接即可:
<div className={`${styles.singleNews__image} ${styles.featured}`} style={{ backgroundImage: `url(${post.image})` }}/>
写法2:数组拼接
如果类名数量较多,用数组join更易维护:
<div className={[styles.singleNews__image, styles.featured].join(' ')} style={{ backgroundImage: `url(${post.image})` }}/>
写法3:使用classnames工具(推荐复杂场景)
如果需要根据条件动态切换类名,可使用React生态常用的classnames工具库:
- 安装依赖
npm install classnames
- 代码中调用
import cn from 'classnames'; import styles from './SingleNews.module.scss'; // 基础用法 <div className={cn(styles.singleNews__image, styles.featured)} style={{ backgroundImage: `url(${post.image})` }}/> // 条件启用类名示例:只有isFeatured为true时才加featured类 <div className={cn(styles.singleNews__image, {[styles.featured]: isFeatured})} style={{ backgroundImage: `url(${post.image})` }}/>
内容的提问来源于stack exchange,提问作者John John
相关产品推荐
相关产品推荐

