0
点赞
收藏
分享

微信扫一扫

React的Context在类组件和函数式组件中的使用

践行数据分析 2022-04-18 阅读 211

1.引入context,并解构出来

import React, { Component } from 'react'
const NameContext = React.createContext()
//Provider是给类组件  Consumer是类函数都可以 使用
const { Provider, Consumer } = NameContext

2.定义一个State

state = { username: 'tom', age: 18 }

3.将你需要传递给子孙组件的值用Provider包裹,现在这个value是一个公共值,都能拿到

    return (
      <div>
        <h1>我是a组件</h1>
        <h2>我的用户名是:{username}</h2>
        <Provider value={{ username, age }}>
          <B></B>
        </Provider>
        <hr />
      </div>
    )
  }

4.在子孙组件声明后接收,使用static contextType = NameContext接收即可

class C extends Component {
  static contextType = NameContext
  render() {
    console.log(this.context);
    return (
      <div>
        <h1>我是c组件</h1>
        <h2>我的用户名是:{this.context.age}</h2>
      </div>
    )
  }
}

如果是函数式组件 那么使用Consumer

function C() {
  return (
    <div>
      <h1>我是c组件</h1>
      <h2>我的用户名是:
        <Consumer>
          {
            value => {
              return `${value.username}我今年${value.age}`
            }
          }
        </Consumer>
      </h2>

    </div>
  )
}
6.整体代码如下
import React, { Component } from 'react'

const NameContext = React.createContext()
const { Provider, Consumer } = NameContext
export default class Home extends Component {
  state = { username: 'tom', age: 18 }


  render() {
    const { username, age } = this.state
    return (
      <div>
        <h1>我是a组件</h1>
        <h2>我的用户名是:{username}</h2>
        <Provider value={{ username, age }}>
          <B></B>
        </Provider>

        <hr />
      </div>
    )
  }
}

class B extends Component {
  render() {
    return (
      <div>
        <h1>我是b组件</h1>
        <h2>我的用户名是:</h2>
        <C></C>
      </div>
    )
  }
}

// class C extends Component {
//   static contextType = NameContext
//   render() {
//     console.log(this.context);
//     return (
//       <div>
//         <h1>我是c组件</h1>
//         <h2>我的用户名是:{this.context.age}</h2>
//       </div>
//     )
//   }
// }


function C() {
  return (
    <div>
      <h1>我是c组件</h1>
      <h2>我的用户名是:
        <Consumer>
          {
            value => {
              return `${value.username}我今年${value.age}`
            }
          }
        </Consumer>
      </h2>

    </div>
  )
}

举报

相关推荐

0 条评论