This is the seventh day of my participation in the August More Text Challenge. For details, see: August More Text Challenge

\

1. Consider: What to do when an App component passes data to a Child component

  • How to handle this: use props to pass the props down.

  • Better approach: Use Context
  • Function: Pass data across components (e.g., themes, languages). Directly from the App component to the Child

2. How to use Context:

  • Call react.createcontext () to create the Provider and Consumer components
const {Provider,Consumer} = React.createContext()
Copy the code
  • Use the Provider component as the parent node
<Provider>
	<div className="App">
		<Child1/>
	</div>
</Provider>
Copy the code
  • Set the value attribute to indicate the data to be passed
<Provider value="pink">
Copy the code
  • The Consumer component is called to receive the data
 <Consumer>
    {/ * * /}
    {
         data= > <span>{data}</span>
    }
 </Consumer>
Copy the code

3. Complete code:

// Modular syntax in ES6
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

// Create context to get two components
const { Provider, Consumer } = React.createContext()

class App extends React.Component {
  render() {
    return (
      <Provider value="pink">
        <div className="app">
          <Node />
        </div>
      </Provider>)}}const Node = props= > {
  return (
    <div className="node">
      <SubNode />
    </div>)}const SubNode = props= > {
  return (
    <div className="subnode">
      <Child />
    </div>)}const Child = props= > {
  return (
    <div className="child">
      <Consumer>{/* callback */} {data =><span>{data}</span>
        }
      </Consumer>
    </div>
  )
}
ReactDOM.render(<App />.document.getElementById('root'))
Copy the code

4. Conclusion:

  • If two components are nested at multiple levels, you can use Context to communicate with each other
  • Context provides two components: Provider and Consumer
  • Provider: Provides data
  • Consumer: Used to receive data