react context如何使用

1. 创建Context

首先,你需要创建一个Context对象。这可以通过React.createContext方法完成。

复制代码
// src/MyContext.js
import React from 'react';

const MyContext = React.createContext();

export default MyContext;

2. 提供Context值

使用Context.Provider组件来提供上下文值。你可以将Context.Provider包裹在需要访问上下文的组件树的顶部,并通过value属性传递需要共享的数据。

复制代码
// src/App.js
import React from 'react';
import MyContext from './MyContext';
import ChildComponent from './ChildComponent';

function App() {
  const sharedData = {
    name: 'Kimi',
    age: 25
  };

  return (
    <MyContext.Provider value={sharedData}>
      <ChildComponent />
    </MyContext.Provider>
  );
}

export default App;

3. 使用useContext Hook

在需要访问上下文的组件中,使用useContext Hook来获取上下文值。

复制代码
// src/ChildComponent.js
import React, { useContext } from 'react';
import MyContext from './MyContext';

function ChildComponent() {
  const { name, age } = useContext(MyContext);

  return (
    <div>
      <p>Name: {name}</p>
      <p>Age: {age}</p>
    </div>
  );
}

export default ChildComponent;

4. 使用useContextuseState结合

你也可以结合useState来更新上下文值。例如,你可以在Context.Provider中使用useState来管理状态,并通过value属性传递状态和更新状态的函数。

复制代码
// src/App.js
import React, { useState } from 'react';
import MyContext from './MyContext';
import ChildComponent from './ChildComponent';

function App() {
  const [sharedData, setSharedData] = useState({
    name: 'Kimi',
    age: 25
  });

  return (
    <MyContext.Provider value={{ sharedData, setSharedData }}>
      <ChildComponent />
    </MyContext.Provider>
  );
}

export default App;

5. 在子组件中更新上下文值

在子组件中,你可以使用setSharedData来更新上下文值。

复制代码
// src/ChildComponent.js
import React, { useContext } from 'react';
import MyContext from './MyContext';

function ChildComponent() {
  const { sharedData, setSharedData } = useContext(MyContext);

  const handleUpdate = () => {
    setSharedData({
      ...sharedData,
      age: sharedData.age + 1
    });
  };

  return (
    <div>
      <p>Name: {sharedData.name}</p>
      <p>Age: {sharedData.age}</p>
      <button onClick={handleUpdate}>Increment Age</button>
    </div>
  );
}

export default ChildComponent;

6. 使用useReducerContext

如果你需要更复杂的状态管理逻辑,可以结合useReducerContext。例如:

复制代码
// src/MyContext.js
import React, { useReducer } from 'react';

const initialState = {
  name: 'Kimi',
  age: 25
};

const reducer = (state, action) => {
  switch (action.type) {
    case 'INCREMENT_AGE':
      return { ...state, age: state.age + 1 };
    default:
      return state;
  }
};

const MyContext = React.createContext();

export const MyContextProvider = ({ children }) => {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <MyContext.Provider value={{ state, dispatch }}>
      {children}
    </MyContext.Provider>
  );
};

export default MyContext;

7. 在子组件中使用useReducerContext

在子组件中,你可以使用dispatch来更新状态。

复制代码
// src/ChildComponent.js
import React, { useContext } from 'react';
import MyContext from './MyContext';

function ChildComponent() {
  const { state, dispatch } = useContext(MyContext);

  const handleIncrement = () => {
    dispatch({ type: 'INCREMENT_AGE' });
  };

  return (
    <div>
      <p>Name: {state.name}</p>
      <p>Age: {state.age}</p>
      <button onClick={handleIncrement}>Increment Age</button>
    </div>
  );
}

export default ChildComponent;

8. 提供Context

确保在顶层组件中使用MyContextProvider来提供上下文。

复制代码
// src/App.js
import React from 'react';
import MyContextProvider from './MyContext';
import ChildComponent from './ChildComponent';

function App() {
  return (
    <MyContextProvider>
      <ChildComponent />
    </MyContextProvider>
  );
}

export default App;
相关推荐
LinXunFeng5 小时前
Obsidian - 使用 Share Note 分享笔记并自部署
前端·笔记·github
乘风gg9 小时前
为什么AI 时代来临,大部分人吃不到红利
前端·ai编程·claude
恋猫de小郭9 小时前
Android 限制侧载新进展,谷歌联合国内厂商推验证计划
android·前端·flutter
IT_陈寒9 小时前
Redis内存爆了,原来我漏掉了这个致命配置
前端·人工智能·后端
恋猫de小郭9 小时前
解读 Android 17 全新内存限制,有没有“豁免”后门?
android·前端·flutter
Hyyy10 小时前
理解LLM的基本工作原理:预训练、微调、推理的区别
前端
Gatlin11 小时前
前端逆向与反逆向:一场猫鼠游戏的底层逻辑与实战
前端
代码煮茶11 小时前
React 组件封装方法论 —— 以 Todo App 为例
javascript·react.js
Pedantic11 小时前
本地通知(Local Notifications)学习笔记
前端
任沫11 小时前
Agent之Function Call
javascript·人工智能·go