Skip to content

React Context ​

🎯 概述 ​

React Context 提供了一种在组件树中传递数据的方法,无需逐层传递 props。

📚 基本使用 ​

创建 Context ​

javascript
import { createContext } from 'react'

const ThemeContext = createContext('light')

使用 Provider ​

javascript
import { ThemeContext } from './ThemeContext'

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <Toolbar />
    </ThemeContext.Provider>
  )
}

使用 Consumer ​

javascript
import { useContext } from 'react'
import { ThemeContext } from './ThemeContext'

function Button() {
  const theme = useContext(ThemeContext)
  return <button className={theme}>Button</button>
}

🎯 最佳实践 ​

  1. 将 Context 与状态管理结合
  2. 避免过度使用 Context
  3. 拆分不同的 Context

React Context 简化数据传递! ⚛️