天天看点

react Hooks :useContext的使用

import React, { Component, useState, createContext, useContext } from 'react'

const countContext = createContext()//创建Context实例对象

// 基础写法
class Foo extends Component {
  render() {
    return (
      <countContext.Consumer>
        {
          count => <h1>{count}</h1>
        }
      </countContext.Consumer>
    )
  }
}

//contextType写法
class Bar extends Component {
  static contextType = countContext //contextType是静态的
  render() {
    const count = this.context
    return (
      <h1>{count}</h1>
    )
  }
}

//useContext写法
function Counter() {
  const count = useContext(countContext)
  //调用useContext获取count,参数就是Context实例对象countContext
  //在函数组件中,可以获取成千上万噶Context
  return (
    <h1>{count}</h1>
  )
}
function APP(props) {

  const [count, setCount] = useState(0)

  return (
    <div>
      <button
        type="button"
        onClick={() => { setCount(count + 1) }}
      >
        Click({count})
      </button>
      <countContext.Provider value={count}>
        <Foo />
        <Bar />
        <Counter />
      </countContext.Provider>
    </div>
  )
}

export default APP