【发布时间】:2019-11-20 07:21:53
【问题描述】:
我正在尝试保留用户可以从单选按钮中选择的页面背景。背景随着选择的选项而变化,但是当我重新加载页面时它不会保留其值,并且它也不会应用任何指定的颜色,而是应用来自 className 的颜色,直到我单击其中一个单选按钮。
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
theme: true
};
}
componentDidMount() {
const theme = localStorage.getItem("theme");
this.setState({ theme });
}
componentDidUpdate() {
localStorage.setItem("theme", this.state.theme);
}
toggleTheme =() => {
this.setState({
theme: !this.state.theme
});
}
render() {
let bgStyle
if(this.state.theme === true){
bgStyle = {
backgroundColor:"#3B3B3B",
}
}else if(this.state.theme === false){
bgStyle={
backgroundColor:"#ffffff",
}
}
return (
<div style={bgStyle} className="overall"></div>
);
}
}
切换背景颜色的代码在这里
class Menu extends React.Component {
handleChange = (event) =>{
this.props.toggleTheme();
}
render() {
<form>
<label>
<input
type="radio"
value="Dark"
checked={this.props.theme === true}
onChange={this.handleChange}
/>
Dark
</label>
<label>
<input
type="radio"
value="Light"
checked={this.props.theme === false}
onChange={this.handleChange}
/>
Light
</label>
</form>
);
}
}
【问题讨论】:
-
在渲染中删除
console.log(this.state.theme)并显示每个日志 -
App.js:81 trueApp.js:81 true
标签: javascript reactjs local-storage