Skip to content

Commit

Permalink
feat: add react some logs
Browse files Browse the repository at this point in the history
  • Loading branch information
leezozz committed Dec 28, 2023
1 parent c8e0eaf commit 735c2b5
Showing 1 changed file with 91 additions and 1 deletion.
92 changes: 91 additions & 1 deletion docs/blog/frameSeries/react/9.记录.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,8 @@ const columns =
```

### 2. 场景:
一个tsx文件中,尽量不要写多个组件,**每个组件都抽离成单独的文件**,避免重复渲染,多次更新造成问题!!!
- 一个tsx文件中,尽量不要写多个组件,**每个组件都抽离成单独的文件**,避免重复渲染,多次更新造成问题!!!
- 组件中尽量少声明useState,可以使用已声明useState的衍生出来的变量

### 3. antd组件库中的form
form.Item会默认传递value、onChange
Expand All @@ -164,3 +165,92 @@ form.Item会默认传递value、onChange
<CustomInput />
</Form.Item>
```

### 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 (
<Child onFormSubmit={onChildFormSubmit} />
)
}
```
```tsx
// 子组件
function Child({onFormSubmit}) {

const onSubmit = () => {
// 处理表单校验
// 提交表单数据给接口

onFormSubmit(); // 提交后调用父组件方法
}

return (
<Form>
<button onClick={onSubmit}>提交</button>
</Form>
)
}
```
2. 子组件影响父组件的状态变化
```tsx
// 创建Context
const CounterContext = React.createContext();
```
```tsx
// 父组件提供Context值
export const Parent = () => {

const [count, setCount] = useState(0);

return (
<CounterContext.Provider
value={{count, setCount}}
>
<Child />
</CounterContext.Provider>
)
}
```
```tsx
// 子组件消费Context更新父组件状态
export const Child = () => {
const { setCount } = useContext(CounterContext);

const onSubmit = () => {
// submit logic
setCount(count + 1);
}

return <div>...</div>;
}
```
3. 可以使用EventBus。

0 comments on commit 735c2b5

Please sign in to comment.