ReactJS
字符数量统计: 942
useReducer Demo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import { useReducer } from 'react';
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
return state;
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
<button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
</div>
);
}
React.Children提供了一些实用方法来处理props.children。其中常用的功能有React.Children.map()、React.Children.forEach()、React.Children.count()、React.Children.only()和React.Children.toArray()。
2.1. Table of Content (ToC) 开发
ToC 是一个常见的网页组件,用于显示文章或页面的目录。在React中,我们可以使用React.Children来处理props.children,从而实现一个简单的ToC组件。 由于React.Children.map只遍历一层子节点,而我们需要递归所有子节点,我们需要手动对props.children进行递归处理。