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

感谢你读到这里。

这座小站更像一份持续维护的“终端笔记”:记录我解决问题的过程,也记录走过的弯路。

如果这篇内容对你有一点点帮助:

  • 点个赞 / 收藏一下,方便你下次回来继续翻
  • 欢迎在评论区补充你的做法(或者指出我的疏漏)
  • 想持续收到更新:可以订阅 RSS(在页面底部)

我们下篇见。


More Posts

评论

评论 (0)

请先登录后再发表评论

加载中...