From 6b44442ff740da8625735abaec2a2e6b8da08cdf Mon Sep 17 00:00:00 2001 From: qhan Date: Fri, 10 May 2024 16:24:53 +0800 Subject: [PATCH] feat(site/blog): add code examlpe of code snippets of react context --- .../md/code-snippets/react-context-api.md | 41 ++++++++++++++++++- 1 file changed, 39 insertions(+), 2 deletions(-) diff --git a/site/blog/md/code-snippets/react-context-api.md b/site/blog/md/code-snippets/react-context-api.md index edc302f..9fdc720 100644 --- a/site/blog/md/code-snippets/react-context-api.md +++ b/site/blog/md/code-snippets/react-context-api.md @@ -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(); + const setDrawData = (v: number[][]) => setInnerDrawData(v); + + // 添加其它状态值维护 + // ..... + + // 暴露数据对象 + return { drawData, setDrawData }; +} + +const LandsContext = createContext({}); + +function ProviderLands({ children }: { children: React.ReactNode }) { + const lands = useProvideLands(); + return {children}; +} + +// 添加自定义 hooks 包裹 LandsContext 简化使用方式 +function useLandsContext() { + return useContext(LandsContext); +} + +export { ProviderLands, useLandsContext }; +``` + +- 示例二 ```tsx // 源码来自鲁班系统 import React, { useContext, createContext, useState } from 'react'; @@ -50,7 +86,8 @@ function useWsInstance() { export { ProvideWsInstance, useWsInstance }; ``` -- 示例二 + +- 示例三 使用 `useReducer` 实现多状态管理 ```tsx import React, { createContext, useContext, useReducer } from 'react';