Context
Context, which allows a child component to call root component data within a certain range
import React from "react";
import { render } from "react-dom";
// Create a Context object
// "light" is the default.
const ThemeContext = React.createContext("light");
// Set the alias, in the React Developer Tools, as the alias
ThemeContext.displayName = "MyDisplayName";
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
them: "dark"};this.onClick = this.onClick.bind(this)}onClick() {
console.log("Updated data in App")
this.setState({
them: this.state.them == "light" ? "dark" : "light"})}render() {
// Use a Provider to pass the current theme to the following component tree.
// Any component, no matter how deep, can read this value.
// In this case, we pass "dark" as the current value.
return (
<>
<div><ThemeContext.Provider>Value passes in data shared by the context</div>
<div>be<ThemeContext.Provider>Contains subcomponents for which data can be shared without being passed layer by layer</div>
<ThemeContext.Provider value={this.state.them}>
<Toolbar />
</ThemeContext.Provider>
<div onClick={this.onClick}>onClick</div>
</>); }}// Intermediate components no longer have to specify the theme to pass down.
function Toolbar(props) {
In stateless functional components, context can be called using useContext
const theme = React.useContext(ThemeContext)
console.log(theme)
return (
<div>
<ThemedButton />/* Consumer call context */}<div>The value in context. Consumer is the value passed in by context. Provider</div>
<ThemeContext.Consumer>
{value => (
<div>{value}</div>
)}
</ThemeContext.Consumer>
</div>
);
}
// Toolbar.contextType = ThemeContext;
class ThemedButton extends React.Component {
// Specify contextType to read the current theme context.
// React will find the nearest theme Provider and use its value.
// In this case, the current theme value is "dark".
render() {
return (
<div>
<button>{this.context}</button>
<ThemeContext.Consumer>
{value => (
<button>{value}</button>
)}
</ThemeContext.Consumer>
</div>); }}// contextType must be specified to use context.consumer
ThemedButton.contextType = ThemeContext;
render(<App />.document.getElementById("react-container"));Copy the code
//end