Skip to content

useContext

介绍

useContext 是一个 React Hook,用于在组件中访问上下文。上下文是一个组件树中的变量,它可以在组件树中传递给任何组件。

示例

  1. 使用 createContext 方法创建一个上下文对象 Ctx
  2. 在顶层组件(App)中通过 Ctx.Provider 组件提供数据
  3. 在底层组件(B)中通过 useContext 钩子函数获取消费数据
jsx
import { createContext, useContext } from 'react'

const MsgCtx = createContext('default value')

function A() {
  return (
    <div>
      <div>A 组件</div>
      <B />
    </div>
  )
}

function B() {
  const msg = useContext(MsgCtx)

  return <div>B 组件 - {msg}</div>
}

function App() {
  const msg = 'hello world'
  return (
    <>
      <MsgCtx.Provider value={msg}>
        <div>UseContext</div>
        <A />
      </MsgCtx.Provider>
    </>
  )
}

基于 MIT 许可发布