Skip to content

Commit

Permalink
feat(site/blog): add code examlpe of code snippets of react context
Browse files Browse the repository at this point in the history
  • Loading branch information
qhanw committed May 10, 2024
1 parent cc62a65 commit 6b44442
Showing 1 changed file with 39 additions and 2 deletions.
41 changes: 39 additions & 2 deletions site/blog/md/code-snippets/react-context-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,43 @@ category: react
tags: [react, javascript]
---

- 示例一
- 示例一 最基本配置
```tsx
import { useContext, createContext, useState } from 'react';

type LandsContextState = {
drawData?: number[][];
setDrawData?: (v: number[][]) => void;
};

function useProvideLands() {
// 设置状态 drawData 值
const [drawData, setInnerDrawData] = useState<number[][]>();
const setDrawData = (v: number[][]) => setInnerDrawData(v);

// 添加其它状态值维护
// .....

// 暴露数据对象
return { drawData, setDrawData };
}

const LandsContext = createContext<LandsContextState>({});

function ProviderLands({ children }: { children: React.ReactNode }) {
const lands = useProvideLands();
return <LandsContext.Provider value={lands}>{children}</LandsContext.Provider>;
}

// 添加自定义 hooks 包裹 LandsContext 简化使用方式
function useLandsContext() {
return useContext(LandsContext);
}

export { ProviderLands, useLandsContext };
```

- 示例二
```tsx
// 源码来自鲁班系统
import React, { useContext, createContext, useState } from 'react';
Expand Down Expand Up @@ -50,7 +86,8 @@ function useWsInstance() {

export { ProvideWsInstance, useWsInstance };
```
- 示例二

- 示例三 使用 `useReducer` 实现多状态管理
```tsx
import React, { createContext, useContext, useReducer } from 'react';

Expand Down

0 comments on commit 6b44442

Please sign in to comment.