Context is easy to use in React, and the official website makes it very clear. However, if you rush to use Context, you will encounter some problems. Here is a summary of the problems I encountered in using Context for the first time.

1, export const ThemeContext = react.createcontext ();

Create a Context object


2

  <ThemeContext.Provider        value={{          model: this.state.model,          changeModel: this.changeModel,          validate,          changeError: this.changeError,          error: this.state.error,        }}      >Copy the code

The parent component wraps themecontext.provider and writes all the data that needs to be passed inside the value

3. In child components

import { ThemeContext } from ‘.. /Form’;

Introduce the ThemeContext component

4,

<ThemeContext.Consumer> {(context) => ( <div> <WrapComponent value={context.model[v_model]} onChange={this.onChange} onBlur={this.onBlur} {... this.props} /> {context.error[v_model] ? ( <div className={styled.message}>{context.error[v_model]}</div> ) : ( <div className={styled.message} /> )} </div> )} </ThemeContext.Consumer>Copy the code

When using context in Consumer, you need to use it as a function, otherwise an error will be reported

Myclass.contexttype = MyContext;

The contextType property mounted on the class is reassigned to a Context object created by react.createcontext (). This allows you to use this.context to consume the value of the most recent context. You can access it in any lifecycle, including the Render function.