So what are the properties of Context?

  • React. CreateContext: Creates a context object
  • Context.Provider: allows sub-components to consume Context
  • Context.consumer: A consuming component that consumes the value defined in the nearest provider and destroys the default value of the Context if it does not exist
  • Class.contextType: Allows the value of the most recent context to be destroyed
  • Context.displayName: Determines the name of the Context display

How do YOU develop components using Context?

Use the Class. ContextType

import './App.css';
import React from 'react';
const myContext = React.createContext('defaultContext');

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            name: '123'
        };
    }
    render() {
        return (
            <myContext.Provider value={this.state}>
                <Toolbar theme="dark" />;
            </myContext.Provider>
        );
    }
}

function Toolbar(props) {
    return (
        <div>
            <ThemedButton theme={props.theme} />
        </div>
    );
}

class ThemedButton extends React.Component {
    render() {
        return <div>{this.context.name}</div>;
    }
}
ThemedButton.contextType = myContext;
export default App;
Copy the code

Use the Context. Consumer

import './App.css';
import React from 'react';
const myContext = React.createContext('defaultContext');

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            name: '123'
        };
    }
    render() {
        return (
            <myContext.Provider value={this.state}>
                <Toolbar theme="dark" />;
            </myContext.Provider>
        );
    }
}

function Toolbar(props) {
    return (
        <div>
            <ThemedButton theme={props.theme} />
        </div>
    );
}

class ThemedButton extends React.Component {
    render() {
        return (
            <myContext.Consumer>
                {({ name }) => <div>{name}</div>}
            </myContext.Consumer>
        );
    }
}

export default App;
Copy the code

Why does React not recommend using Context first?

  • Breaking dependencies between component trees, and using context incorrectly can make data management complicated and messy
  • This is an experimental API that may be scrapped in the future

Where else can you get Context directly other than by instance properties?

  • Stateless component parameters are directly obtained
  • The constructor
  • Life cycle function shouldComponentUpdate componentWillReceiveProps componentWillUpdate

What is childContextTypes? What does it do

ChildContextTypes is used to define the context data type