problem description
found a problem when learning the react official document context. The constructor declares an arrow function and a state,. If you put the state on the arrow function, there is no way to change the skin of the button (the button clicks unresponsive, but will not report an error). Just put it in the back.
context- father-son coupling-button skin change
related codes
import...
//Context
import {ThemeContext, themes} from "./theme-context";
//
import ThemeTogglerButton from "./theme-toggler-btn";
class App extends React.Component {
constructor(props) {
super(props);
//state
/*this.state = {
theme: themes.dark,
toggleTheme: this.toggleTheme
}*/
this.toggleTheme = () => {
this.setState(state => ({
theme:
state.theme === themes.dark
? themes.light
: themes.dark
}))
}
//state
this.state = {
theme: themes.dark,
toggleTheme: this.toggleTheme
}
}
render() {
return (
<ThemeContext.Provider value={this.state}>
<Content/>
</ThemeContext.Provider>
)
}
}
function Content() {
return (
<div>
<ThemeTogglerButton/>
</div>
)
}
ReactDOM.render(
<App/>,
document.getElementById("root")
)
the rest of the code can be found in the official documentation
it is estimated that bosses who are impatient or not interested in this question will not bother to look at it, so please those who are also learning from react
.