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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
// useState
export function StateExample() {
/**
* show 被推断为 boolean
* setShow 被推断为 React.Dispatch<React.SetStateAction<boolean>>
*/
const [show, setShow] = React.useState(false);
/**
* user 被推断为 User | null
* setUser 被推断为 React.Dispatch<React.SetStateAction<User | null>>
*/
type User = {};
const [user, setUser] = React.useState<User | null>(null);
return null;
}
// useReducer
const initialState = { count: 0 };
type ActionType =
| { type: 'add'; payload: number }
| { type: 'dec'; payload: number };
function reducer(state: typeof initialState, action: ActionType) {
switch (action.type) {
case 'add':
return { count: state.count + action.payload };
case 'dec':
return { count: state.count - action.payload };
default:
return { count: state.count };
}
}
export function ReducerExample() {
/**
* state 被推断为 {count: number}
* dispatch 被推断为 React.Dispatch<ActionType>
*/
const [state, dispatch] = React.useReducer(reducer, initialState);
return (
<div>
<span>{state.count}</span>
<button onClick={() => dispatch({ type: 'add', payload: 1 })}>+</button>
<button onClick={() => dispatch({ type: 'dec', payload: 1 })}>-</button>
</div>
);
}
// useRef
type timerType = ReturnType<typeof setTimeout> | null; // 获取 setTimeout 的返回值
export function DelayShow({ delay = 3000 }: { delay?: number }) {
const timer = React.useRef<timerType>(null);
const [show, setShow] = useState(false);
useEffect(() => {
setShow(false);
timer.current = setTimeout(() => {
setShow(true);
}, delay);
return () => {
if (timer.current) {
clearTimeout(timer.current);
}
};
}, [delay]);
return show ? <span>TikTok</span> : null;
}
export const DOMRef: React.FC = ({ children }) => {
const divRef = React.useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
console.log(divRef.current);
}, []);
return <div ref={divRef}>{children}</div>;
};
// useContext
type ThemeType = { theme: string };
export const Theme = React.createContext<ThemeType>({ theme: 'dark' });
export function ConsumerExample() {
const value = React.useContext<ThemeType>(Theme);
return <span>{value.theme}</span>;
}
|