1024programmer Blog How to use the context in react_is the context of react a one-way data flow_tsuyoii’s blog

How to use the context in react_is the context of react a one-way data flow_tsuyoii’s blog

class=”markdown_views prism-atom-one-dark”>

context can be used to pass parameters from parent components to child components or from grandparent components to grandchild components.
Note that data flow is one-way, and child components cannot be passed to parent components

Usage:

  1. In the parent component MyComponent
const AContext = React.createContext(initial value)
 function MyComponent(){
     
     render (){
     
         AContext.provider value={
     this.state}   //You can pass an object
             B/B
          /AContext.provider>
     }
 }
 
  1. const AContext = React.createContext (initial value)//The initial value here is similar to the initial value of useState, you can pass an empty value
 AContext.provider value={
     this.state}   //You can pass an object
       B/B
   /AContext.provider>
 
  1. At this time, if component B contains subcomponent C, you don’t need to specify the data that needs to be passed down, and C will get the
    subcomponent B component by default
function B(){
     
     return(
         C/C
     );
 }
 
  1. Specify the contextType to read the current context value, and React will find the nearest Provider to the upper layer
    In the grandson component C
    Introduce AContext from the parent component MyComponent
function C(){
     
         static contextType = AContext;
         render (){
     
             return <Button theme={
     this.context}   //theme value is this.state in the parent component MyComponent component
         }
 }
 

Compared with props and state, React’s Context can realize cross-level component communication

https://zhuanlan.zhihu.com/p/110331535
https://zh-hans.reactjs.org/docs/context.html

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/how-to-use-the-context-in-react_is-the-context-of-react-a-one-way-data-flow_tsuyoiis-blog/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索