diff --git "a/docs/blog/frameSeries/react/9.\350\256\260\345\275\225.md" "b/docs/blog/frameSeries/react/9.\350\256\260\345\275\225.md" index 500d3899..b270062a 100644 --- "a/docs/blog/frameSeries/react/9.\350\256\260\345\275\225.md" +++ "b/docs/blog/frameSeries/react/9.\350\256\260\345\275\225.md" @@ -150,7 +150,8 @@ const columns = ``` ### 2. 场景: -一个tsx文件中,尽量不要写多个组件,**每个组件都抽离成单独的文件**,避免重复渲染,多次更新造成问题!!! +- 一个tsx文件中,尽量不要写多个组件,**每个组件都抽离成单独的文件**,避免重复渲染,多次更新造成问题!!! +- 组件中尽量少声明useState,可以使用已声明useState的衍生出来的变量 ### 3. antd组件库中的form form.Item会默认传递value、onChange @@ -164,3 +165,92 @@ form.Item会默认传递value、onChange ``` + +### 4. setId保持 +修改、编辑之后重新获取列表,保持当前选中侧边id +```js +setCurrentSelectKey(currentSelectKey => currentSelectKey || data.rules[0]?.id) +``` + +### 5. 子组件点击按钮触发父组件事件 +1. 通过props和回调函数的方式实现(场景:子组件表单提交后,触发父组件列表更新) +```tsx +// 父组件 +import { useState, useEffect } from 'react'; + +function Parent() { + const [list, setList] = useState([]); + + useEffect(() => { + // 初始化加载list + }, []) + + // 当子组件表单提交后重新获取列表 + const onChildFormSubmit = () => { + fetchList().then(newList => { + setList(newList); + }) + } + + return ( + + ) +} +``` + +```tsx +// 子组件 +function Child({onFormSubmit}) { + + const onSubmit = () => { + // 处理表单校验 + // 提交表单数据给接口 + + onFormSubmit(); // 提交后调用父组件方法 + } + + return ( +
+ +
+ ) +} +``` +2. 子组件影响父组件的状态变化 +```tsx +// 创建Context +const CounterContext = React.createContext(); +``` + +```tsx +// 父组件提供Context值 +export const Parent = () => { + + const [count, setCount] = useState(0); + + return ( + + + + ) +} +``` + +```tsx +// 子组件消费Context更新父组件状态 +export const Child = () => { + const { setCount } = useContext(CounterContext); + + const onSubmit = () => { + // submit logic + setCount(count + 1); + } + + return
...
; +} +``` + +3. 可以使用EventBus。 +