A,Context(Context) awareness

  • 1. In some scenarios, you want to pass data across the entire component tree, but you don’t want to manually pass properties at each level. You can go directly toReactUse powerfulcontextAPISolve the above problems
  • 2, in a typicalReactIn applications, data is passedpropsAttributes are passed down from parent to child, but this is extremely cumbersome for certain types of attributes (e.g., locale preference,UITopics), these properties are required by many components in the application.ContextProvides a way to share such values between components without having to explicitly pass them layer by layer through the component treeprops
  • 3. UsedexpressorkoaFrameworks often use context to pass data throughout the project.
  • This article introducesreactIn several common ways of defining and using context, inreactIn the ecosystemredux.react-router-domAll libraries use context to pass data, understandreactContext is good for reading source code in the future.

Steps to use context in a class component

  • 1. Create a context (use a single file for multiple files)

    import React, { Component } from 'react'
    
    // Create a context
    const ColorContext = React.createContext();
    Copy the code
  • Use context in the root component. Provider injection, a vaule property that needs to be passed (the data needs to be passed to the next component, the child component only gets the passed data)

    export default class ContextComponents1 extends Component {
      constructor(props) {
        super(props);
        this.state = {
          color: '# 333',
        }
      }
      changeColor = (color) = > {
        this.setState({ color });
      }
      render() {
        const { color } = this.state;
        return (
          <ColorContext.Provider value={{ color.changeColor: this.changeColor}} >{/* Pass only one color and one changeColor method. Child components can only get these two properties from the context */}<Header />
            <button onClick={()= >Enclosing changeColor (' yellow ')} > yellow</button>
            <button onClick={()= >Enclosing changeColor (' green ')} > green</button>
          </ColorContext.Provider>)}}Copy the code
  • 3. Use context in child components

    class Header extends Component {
      // Define this line if a context is needed in a child component
      static contextType = ColorContext;
      render() {
        console.log(this.context); // Get the color and changeColor methods passed in value from the root component
        return (
          <>
            <h1 style={{ color: this.context.color}} >I'm a header component</h1>
            <Title />
          </>)}}Copy the code

The way context is used in function components

  • 1. Define context

    import React, { Component } from 'react';
    
    const ColorContext = React.createContext();
    Copy the code
  • 2. Define the root component

    export default class ContextComponent2 extends Component {
      state = {
        color: '# 333',
      }
      changeColor = (color) = > {
        this.setState({ color })
      }
      render() {
        const { color } = this.state;
        return( <ColorContext.Provider value={{ color }}> <Header name={'header'} type={1} /> <button onClick={() => </button> <button onClick={() => this.changecolor ('green')}> green </button> </ColorContext.Provider> ) } }Copy the code
  • 3. Use in function components

    function Header(props) {
      console.log(props, 'props attribute')
      return (
        <ColorContext.Consumer>{value => {console.log(value, 'context data ') return (<h1 style={{ color: value.color}} >I'm a header component</h1>)}}</ColorContext.Consumer>)}Copy the code

Four, the use ofhooksNew property creation context

  • 1. Create a context

    import React, { Component, useContext, useState } from 'react';
    const ColorContext = React.createContext();
    Copy the code
  • 2. Root component

    export default() = > {let [color, setColoer] = useState('# 333');
    
      return (
        <ColorContext.Provider value={{ color}} >
          <Header />
          <button onClick={()= >SetColoer (' yellow ')} > yellow</button>
          <button onClick={()= >SetColoer (' green ')} > green</button>
        </ColorContext.Provider>)}Copy the code
  • 3. Use in child components

    function Header(props) {
      let { color } = useContext(ColorContext);
      console.log(color, 'Context');
      return (
        <>
          <h1 style={{ color: color}} >I'm a header component</h1>
        </>)}Copy the code