Context Hook

2020-05-24  本文已影响0人  percykuang

Context Hook

用于获取上下文数据

使用context:

import React from 'react'

const context = React.createContext()

const Provider = context.Provider
const Consumer = context.Consumer

function Test() {
  return (
    <Consumer>
      { value => <h1>Test, 上下文的值:{ value }</h1> }
    </Consumer>
  )
}

export default function () {
  return (
    <div>
      <Provider value="hello context hook">
        <Test />
      </Provider>
    </div>
  )
}

使用Context Hook:

import React, { useContext } from 'react'

const context = React.createContext()

const Provider = context.Provider

function Test() {
  // 直接获取
  const value = useContext(context)
  return <h1>Test, 上下文的值:{ value }</h1>
}

export default function () {
  return (
    <div>
      <Provider value="hello context hook">
        <Test />
      </Provider>
    </div>
  )
}
上一篇下一篇

猜你喜欢

热点阅读