学习React-16-useContext

使用 useContext 的基本概念

useContext 是 React Hooks 的一部分,用于在函数组件中访问 React 的 Context。Context 提供了一种在组件树中共享数据的方式,避免了逐层传递 props 的繁琐。

创建 Context

需要先通过 React.createContext 创建一个 Context 对象,并设置默认值(可选):

javascript 复制代码
const MyContext = React.createContext(defaultValue);

提供 Context 值

在父组件中使用 Context.Provider 包裹子组件,并通过 value 属性传递数据:

javascript 复制代码
<MyContext.Provider value={/* 共享的数据 */}>
  <ChildComponent />
</MyContext.Provider>

在子组件中消费 Context

在函数组件中通过 useContext 直接获取 Context 的值:

javascript 复制代码
const value = useContext(MyContext);

小栗子

以下是一个完整的示例,展示如何创建、提供和使用 Context:

ts 复制代码
import React, {useState, useContext} from 'react'

interface ThemeContextType {
    theme: string
    setTheme: (theme: string) => void
}
// 声明上下文
const MyContext = React.createContext<ThemeContextType>({} as ThemeContextType)

const style = {
    width: '100px',
    height: '100px',
    backgroundColor: 'black',
    marginTop: '10px'
}

const Child = () => {
    const theme = useContext(MyContext)
    return (
        <div>
            子组件
            <button onClick={() => theme.setTheme('dark')}>子组件切换</button>
            <div style={{...style, backgroundColor: theme.theme == 'light'? 'green': 'black'}}>
            
        </div>
        </div>
        
    )
}

const Parent = () => {
    // 使用上下文
    const theme = useContext(MyContext)
    return (
        <div>
            父组件
            <button onClick={() => theme.setTheme('light')}>父组件切换</button>
            <div style={{...style, backgroundColor: theme.theme == 'light'? 'green': 'black'}}></div>
            <Child />
        </div>
    )
}

export const App = () => {
    const [theme, setTheme] = useState('light')
    return (
        <div>
            <button onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}>主题切换</button>
            <MyContext.Provider value={{theme, setTheme}}>
                <Parent />
            </MyContext.Provider>
        </div>
    )
}

export default App

注意:上面的栗子是React18的语法,React19中已经不需要使用Provider。

ts 复制代码
// React 19的语法
<MyContextvalue={{theme, setTheme}}>
      <Parent />
</MyContext>

多 Context 使用

一个组件可以消费多个 Context,只需多次调用 useContext

javascript 复制代码
const user = useContext(UserContext);
const theme = useContext(ThemeContext);

性能优化

避免因不必要的重新渲染导致性能问题,可以将 Context 的值通过 useMemouseState 进行优化:

javascript 复制代码
const [value, setValue] = useState(initialValue);
const memoizedValue = useMemo(() => ({ value, setValue }), [value]);

return (
  <MyContext.Provider value={memoizedValue}>
    {/* 子组件 */}
  </MyContext.Provider>
);

注意事项

  • 默认情况下,useContext 会监听 Context 值的变化,即使父组件使用 React.memoshouldComponentUpdate,子组件仍会重新渲染。
  • 如果 Context 的 value 是一个新对象(如 value={``{ theme }}),每次渲染都会触发子组件更新,应避免直接传递内联对象。
  • 如果重复嵌套使用并且使用的值是相同的则里层的值会覆盖外层的值。
相关推荐
无心使然1 分钟前
Openlayers调用ArcGis要素服务之一 ——要素查询 (/query)
前端·javascript·数据可视化
ZC跨境爬虫2 分钟前
跟着 MDN 学 HTML day_1:(全套原生Input+表单结构拆解)
前端·css·ui·html
焰火19996 分钟前
[前端]单文件上传组件
前端·vue.js
kyriewen118 分钟前
Next.js部署:从本地跑得欢,到线上飞得稳
开发语言·前端·javascript·科技·react.js·前端框架·ecmascript
慕容卡卡12 分钟前
Claude 使用神器(web页面)--CloudCLI UI
java·开发语言·前端·人工智能·ui·spring cloud
咬_咬13 分钟前
go语言学习(函数)
开发语言·学习·golang
JarvanMo22 分钟前
搞懂这 5 个 AI 术语,你就超过了 90% 的人
前端·后端
IT_陈寒28 分钟前
Vite的HMR怎么突然失效了?原来是我太年轻
前端·人工智能·后端
豆瓣鸡29 分钟前
Agent实战练习
java·python·学习
ZC跨境爬虫33 分钟前
Apple官网复刻第二阶段day_6:(统一页脚模块封装+CSS公共复用体系落地)
前端·css·ui·重构·html