[英]Why doesnt my Scss mixin work in my React Project?
所以我有一个新的 React 项目,我在其中尝试 SCSS 作为样式部分。 我基本上是一个 SCSS 菜鸟,因为我一直使用 Css。 我上网查找有关如何操作的教程,最后得到了以下代码:
// _themes.scss
$themes: (
light: (
color-background: #FAFAFA,
color-card: #FFF
),
dark: (
color-background: #37474F,
color-card: #212121
)
);
// _mixins.scss
@mixin theme-aware($key, $color) {
@each $theme-name, $theme-color in $themes {
.theme-#{$theme-name} & {
#{$key}: map.get(map.get($themes, $theme-name), $color)
}
}
}
//App.module.scss
@import "../../assets/themes/mixins";
.container {
width: 100%;
height: 100%;
@include theme-aware('background', 'color-background');
}
现在我已经尝试了一切:
以下是我目前所知道和理解的:
我不明白什么? 我在网上看到的教程使用了node-scss并且有效,到目前为止我能找到的唯一区别
编辑:: 我终于找到了问题。 如果我不使用 React Router,它确实有效。 我的 App.tsx:
export default function App() {
const dispatch = useDispatch()
const session = useSelector(sessionSelector)
const theme = useSelector(themeSelector)
useEffect(() => {
document.documentElement.className = '';
document.documentElement.classList.add(`theme-${theme.name}`)
}, [theme])
return (
<div>
<Home />
<Routes>
<Route path={paths.home} element={<Outlet />}>
<Route element={<RequireAuth roles={["SUPER"]} />}>
</Route>
<Route element={<RequireAuth roles={["SUPER", "ADMIN"]} />}>
</Route>
<Route element={<RequireAuth roles={["SUPER"]} />}>
</Route>
</Route>
</Routes>
</div>
)
}
如您所见,我将 scss 主题应用于文档本身。 它在我的组件中确实有效,并且所有颜色都发生了变化,但是路由无法识别该类。 为了修复它,我将样式应用于身体,例如:
@import "./assets/themes/mixins";
* {
@include theme-aware('background', 'color-background');
}
如果您不使用 JavaScript,则您没有在反应中使用 .scss 扩展名,那么请确保添加该语言扩展名..
@import
"../../assets/themes/_mixins.scss";
Or
如果您的 mixin scss 文件名不包含 (_) 下划线,则使用此
@import
"../../assets/themes/mixins.scss;
问题出在_mixins.scss
中,您需要导入sass:map
才能使用map.get
或者您也可以直接使用map-get
而无需导入sass:map
并且我已经替换了.theme-#{$theme-name}
中的连字符.theme-#{$theme-name}
在mixins.scss
中带有下划线.theme_#{$theme-name}
。 通过您提供的代码中的这两个更改,将应用适当的主题。
// _themes.scss
$themes: (
light: (
color-background: #FAFAFA,
color-card: #FFF
),
dark: (
color-background: #37474F,
color-card: #212121
)
);
// _mixins.scss
@use "sass:map";
@import "./themes";
@mixin theme-aware($key, $color) {
@each $theme-name, $theme-color in $themes {
.theme_#{$theme-name} & {
#{$key}: map.get(map.get($themes, $theme-name), $color);
}
}
}
//App.module.scss
@import "./mixins";
.container {
width: 100%;
height: 100%;
@include theme-aware('background-color','color-background');
}
//App.module.scss
import styles from "./app.module.scss";
export default function App() {
return (
<div className={styles.theme_dark}>
<div className={styles.container}>
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
</div>
);
}
您可以在这里找到工作示例:- https://codesandbox.io/s/customised-theme-6dvt04?file=/src/_mixins.scss
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.