我想有一个按钮,可以改变我的应用程序的背景颜色。我知道如何做onClick,这将改变我的颜色一次,但我宁愿有一个toggle按钮,而不是。
应用程序.js
function App() {
const [backgroundColor, setBackgroundColor] = useState("#673ab7");
const setStyle = (backgroundColor) => {
setBackgroundColor(!backgroundColor);
};
return (
<div>
<GlobalStyle />
<Header setStyle={setStyle} backgroundColor={backgroundColor} />
<Weather backgroundColor={backgroundColor} />
<Footer />
</div>
);
}
export default App;
带有按钮的组件
export const Header = ({ setStyle, backgroundColor }) => {
return (
<header>
<HeaderApp>
<HeaderTitle>Your Weather App</HeaderTitle>
<ButtonForm onClick={() => setStyle("#fff")}>
{backgroundColor === "#673ab7"
? "Change Background"
: "Previous Background"}
</ButtonForm>
</HeaderApp>
</header>
);
};
首先,你将需要初始化背景的状态。
const Color_One = "#000";
const Color_Two = "#fff";
const [Background, setBackground] = useState(Color_One);
然后你需要创建一个函数,将处理点击事件。
const onChangeBackground = e => {
e.preventDefault();
if(Background === Color_One){
setBackground(Color_Two);
}
else {
setBackground(Color_One);
}
}
最后在你的Button Form组件中。
<ButtonForm onClick={onChangeBackground}>
// some code
</ButtonForm>
你可以使用@Jesse Locas提供的代码,或者你的代码也可以通过一些修改来工作。
const setStyle = (newColor) => {
setBackgroundColor(newColor);
};
将参数backgroundColor改为newColor,这样在设置新的背景色时,你的状态背景色就不会冲突,也就不需要再设置了。!
.
希望对你有所帮助。
谢谢你的帮助