React
一、Ref
1.1 元素
const divRef: RefObject<HTMLDivAreaElement> = useRef(null);
const inputRef: RefObject<HTMLInputAreaElement> = useRef(null);
1.2 对象
const objectRef: RefObject<ObjectType> = useRef(null);
二、Props
2.1 SetStateAction 传递
-
语法一、直接注解
interface ChildPropsType {
setTitle: (value: string) => void;
}
function Child(props: ChildPropsType) {
const {setTitle} = props;
return <div>Child</div>;
}
function App() {
const [title, setTitle] = useState<string>('Vite-React 模板');
return (
<div>
App
<Child setTitle={setTitle} />
</div>
);
} -
语法二、使用
React.Dispatch
注解interface ChildPropsType {
setTitle: React.Dispatch<React.SetStateAction<string>>;
}
function Child(props: ChildPropsType) {
const {setTitle} = props;
return <div>Child</div>;
}
function App() {
const [title, setTitle] = useState<string>('Vite-React 模板');
return (
<div>
App
<Child setTitle={setTitle} />
</div>
);
}
三、State
3.1 数组
3.2 对象
type StateObject = {
a: number;
b: string;
}
const [ stateObject, setStateObject ] = useState<StateObject | null>(null);
stateObject 的类型为: StateObject | null
setStateObject 的类型为: React.Dispatch<React.SetStateAction<StateObject | null>>;
3.3 基础数据
四、Hooks
4.1 原生
import type { useEffect, useLayoutEffect } from 'react';
type EffectHookType = typeof useEffect | typeof useLayoutEffect;
4.2 自定义
-
useUpdateEffect
export const createUpdateEffect: (hook: EffectHookType) => EffectHookType =
(hook) => (effect, deps) => {
const isMounted = useRef(false);
// for react-refresh
hook(() => {
return () => {
isMounted.current = false;
};
}, []);
hook(() => {
if (!isMounted.current) {
isMounted.current = true;
} else {
return effect();
}
}, deps);
};