[react] useContext

24 阅读1分钟

useContext 常用于。祖孙之间通信

import React from 'react'

function Parent(){
  const { theme, setTheme } = useContext(ThemeContext)
  return (
    <div>
      Parent<br/>
      {theme}
      <Child/>
    </div>
  )
}

function Child(){
  const { theme, setTheme } = useContext(ThemeContext)
  return (
    <div>Child<br/>
      {theme}
    </div>
  )
}
const ThemeContext = React.createContext({})

export const App = () => {
  const [theme, setTheme] = useState('light')
  return (
    <ThemeContext.Provider value={{ theme, setTheme }}>
      <Parent/>
    </ThemeContext.Provider>
  )
}

image.png