# react-useContext

2 min read
Table of Contents

主要作用

核心特点

使用场景

注意事项

总结

使用useContext来在组件树中共享数据

Parent switch theme:light
Child switch theme:light
import React, { useContext, useState } from 'react'
import clsx from 'clsx'
const ThemeContext = React.createContext({} as ThemeContextParams)
interface ThemeContextParams {
  theme: string
  setTheme: (theme: string) => void
}
const Child = () => {
  const { theme, setTheme } = useContext(ThemeContext)
  return (
    <div>
      <div
        className="w-65 h-10 ml-4 flex items-center justify-center border border-[#242424] rounded-sm cursor-pointer bg-amber-300 select-none"
        onClick={(e) => {
          e.stopPropagation()
          console.log(222)
          if (theme === 'light') {
            setTheme('dark')
          } else {
            setTheme('light')
          }
        }}
      >
        Child switch theme:{theme}
      </div>
    </div>
  )
}

const Parent = () => {
  const { theme, setTheme } = useContext(ThemeContext)
  return (
    <div>
      <div
        className="w-120 h-20 p-4 border flex items-center justify-center border-[#242424] rounded-sm cursor-pointer bg-amber-500 select-none"
        onClick={() => {
          console.log(111)
          if (theme === 'light') {
            setTheme('dark')
          } else {
            setTheme('light')
          }
        }}
      >
        Parent switch theme:{theme}
        <Child />
      </div>
    </div>
  )
}
function App() {
  const [theme, setTheme] = useState('light')
  return (
    <div
      className={clsx(
        'w-[600px] h-[250px] flex items-center justify-center m-10 border border-amber-700 rounded-xl text-black',
        theme === 'dark' ? 'bg-[#242424]' : 'bg-[#eeeeee]'
      )}
    >
      <ThemeContext.Provider value={{ theme, setTheme }}>
        <Parent />
      </ThemeContext.Provider>
    </div>
  )
}

export default App
My avatar

Thanks for reading my blog post! Feel free to check out my other posts or contact me via the social links in the footer.


More Posts

Comments