[英]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.