我正在嘗試使用 react 制作 SPA,并使用 styled-component 進行樣式和主題更改。當我通過 Javascript 添加類然后嘗試更改主題時遇到的問題,所有由 JavaScript 添加的類都被洗掉。
有人可以告訴我這是什么原因,我該如何解決這個問題?
這是示例,您將看到當您向下滾動時,我在 JavaScript 的幫助下將類添加到標題以提供底部邊框,但是當我使用按鈕切換主題時,添加的類被洗掉。
const themeToggler = () => {
theme === "light" ? setTheme("dark") : setTheme("light");
};
const StyleHeader = styled.header `
background: ${(props) => props.theme.body};
`;
function scrollPos(maxScrollPos) {
let scrollPos = document.documentElement.scrollTop;
if (scrollPos >= maxScrollPos) {
addClassToElement("glow-shadow", ".header");
} else {
removeClassFromElement("glow-shadow", ".header");
}
}
<ThemeProvider theme={theme==="light" ? light : dark}>
<GlobalStyles />
<StyleHeader className={`header pt-3 pb-3 fixed-top`}>
<button onClick={themeToggler}>Toggle</button>
</StyleHeader>
<div className="content">
scrool down to see border on header then click the toggle button to change the theme and border class will be removed
<h1>h1</h1>
</div>
<h1 className="content">h1</h1>
<h1 className="content">h1</h1>
<h1 className="content">h1</h1>
</ThemeProvider>
uj5u.com熱心網友回復:
您需要scrollPos在主題更改后運行您的功能。主題切換器顯然洗掉了元素上除原始類之外的所有類,因此您需要替換它們。像這樣,我們觀察theme屬性的變化:
import React, { useEffect } from "react";
export default function App() {
...
useEffect(() => {
scrollPos(100);
}, [theme, scrollPos]);
...
};
演示
uj5u.com熱心網友回復:
我接受了@isherwood的回答,但我找到了另一種方式,所以我想分享一下。
import React, { useState} from "react";
export default function App() {
...
const [isScrolled, setIsScrolled] = useState(false);
function scrollPos(maxScrollPos) {
let scrollPos = document.documentElement.scrollTop;
if (scrollPos >= maxScrollPos) {
setIsScrolled(true);
} else {
setIsScrolled(false);
}
}
window.addEventListener("scroll", (event) => {
scrollPos(100);
});
return (
<ThemeProvider theme={theme==="light" ? light : dark}>
<GlobalStyles />
<StyleHeader className={`nq-header pt-3 pb-3 fixed-top ${
isScrolled ? "glow-shadow" : ""
}`}>
<button onClick={themeToggler}>Toggle</button>
</StyleHeader>
<div className="content">
scrool down to see border on header then click the toggle button to change the theme and border class will be removed
<h1>h1</h1>
</div>
<h1 className="content">h1</h1>
<h1 className="content">h1</h1>
<h1 className="content">h1</h1>
</ThemeProvider>
)};
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/320850.html
標籤:javascript 反应 推特引导 样式组件
