React study notes - Context

introduce

Context provides a way to share such values ​​between components without having to explicitly pass props through the layers of the component tree

Context provides a way to pass data between component trees without manually adding props to each layer of components

The main application scenario of Context is that many components at different levels need to access the same data. Please use with caution,因为这会使得组件的复用性变差

API

React.createContext

const MyContext = React.createContext(defaultValue);

Use this API to create an object, and the component will read the corresponding value Contextfrom the nearest one . ProviderOnly when the tree species where the component is located does not exist Provider, defaultValuethe parameter will take effect

Context.Provider

<MyContext.Provider value={某个值}/>

Contextobject will return a Providercomponent

  1. Provider accepts a valueproperty and passes it to the consumer component
  2. When the value of the Provider's valueproperty changes, all internal consumer components will be re-rendered
  3. The context will be re-rendered according to the reference identifier, so when passing valuean object to it, you need to pay attention: when re-rendering, unexpected rendering Providermay be triggered . ConsumerTo prevent this, promote the state to valuethe parent node'sstate

Context.Consumer

<MyContext.Consumer>
  {value => /* 基于 context 值进行渲染*/}
</MyContext.Consumer>

Contextobject will return a Consumercomponent

  1. A function is required as a child element, the function receives contexta value, and returns aReact节点
  2. The value passed to the function is equivalent to the provided value valueclosest to this one above the component tree . If there is no counterpart , the argument is equivalent to the one passed tocontextProvidervalueProvidervaluecreateContext()defaultValue

Class.contextType

This property allows you to use this.contextto get Contextthe most recent value. You can access it in any life cycle, including renderfunctions

const MyContext = React.createContext()
class MyClass extends React.Component {
    
    
  render() {
    
    
    let value = this.context;
    /* 基于这个值进行渲染工作 */
  }
}
MyClass.contextType = MyContext

At the same time, you can also use the class property initialization public class fieldsin the experimental syntaxstaticcontextType

const MyContext = React.createContext()
class MyClass extends React.Component {
    
    
  static contextType = MyContext
  render() {
    
    
    let value = this.context;
    /* 基于这个值进行渲染工作 */
  }
}

Context.displayName

contextobject accepts a string displayNamenamed property, which React DevTools uses to determine contextwhat to display

Guess you like

Origin blog.csdn.net/m0_52761633/article/details/122907479
Recommended