React 常用 TypeScript 类型
React 项目通常通过 @types/react、@types/react-dom 获得类型声明。包含 JSX 的文件使用 .tsx,纯类型导入使用 import type。
组件与 Props
用接口或类型别名描述 Props,组件返回值通常可以自动推断,无需额外标注 React.FC:
interface ButtonProps {
title: string;
count?: number;
status: 'loading' | 'idle' | 'success';
onClick: () => void;
}
function ActionButton({ title, count = 0, status, onClick }: ButtonProps) {
return (
<button disabled={status === 'loading'} onClick={onClick}>
{title} ({count})
</button>
);
}
可选属性用 ? 标记,回调用函数签名描述。如果需要显式标注 JSX 返回值,可使用 React.JSX.Element。
children
组件接收 children 时,需要在 Props 中声明,或使用 PropsWithChildren<Props> 添加可选的 children。JSX 和 React.FC 不会自动为自定义 Props 补上这个属性。
import type { PropsWithChildren, ReactNode } from 'react';
interface CardProps {
title: string;
children: ReactNode; // 必需属性;允许值为 null、undefined
}
function Card({ title, children }: CardProps) {
return <section><h2>{title}</h2>{children}</section>;
}
type PanelProps = PropsWithChildren<{ title: string }>;
// { title: string; children?: ReactNode }
ReactNode 表示可渲染内容,包括元素、文本、数组和空值等。只要求单个 React 元素时,可使用 ReactElement;它比 ReactNode 的范围更小。
事件处理
事件泛型指定触发事件的元素类型。访问绑定处理函数的元素时,优先使用 currentTarget:
import type { ChangeEvent, FormEvent, MouseEvent } from 'react';
function SearchForm() {
const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
console.log(event.currentTarget.value);
};
const handleClick = (event: MouseEvent<HTMLButtonElement>) => {
console.log(event.currentTarget.disabled);
};
const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
};
return (
<form onSubmit={handleSubmit}>
<input onChange={handleChange} />
<button type="submit" onClick={handleClick}>搜索</button>
</form>
);
}
键盘和焦点事件可分别使用 KeyboardEvent<T>、FocusEvent<T>。直接在 JSX 中编写处理函数时,参数类型通常可由上下文推断。
Ref
DOM 引用
import { useEffect, useRef } from 'react';
function FocusInput() {
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
inputRef.current?.focus();
}, []);
return <input ref={inputRef} />;
}
DOM 尚未挂载或已经卸载时,current 可能为 null,使用前应检查。
自定义组件的 ref
React 19 的函数组件可以把 ref 作为 Prop 接收:
import type { Ref } from 'react';
interface CustomInputProps {
value: string;
onChange: (value: string) => void;
ref?: Ref<HTMLInputElement>;
}
function CustomInput({ value, onChange, ref }: CustomInputProps) {
return <input ref={ref} value={value} onChange={e => onChange(e.currentTarget.value)} />;
}
React 18 及更早版本需要通过 forwardRef 转发引用:
import { forwardRef } from 'react';
const LegacyInput = forwardRef<HTMLInputElement, Omit<CustomInputProps, 'ref'>>(
({ value, onChange }, ref) => (
<input ref={ref} value={value} onChange={e => onChange(e.currentTarget.value)} />
),
);
这里暴露的是 DOM 节点。需要暴露自定义方法时,使用 useImperativeHandle 并为方法对象定义接口。
State 与自定义 Hook
简单初始值通常可以推断类型;可能为空的对象、空数组等场景需要显式泛型:
import { useState } from 'react';
import type { Dispatch, SetStateAction } from 'react';
interface User {
id: string;
name: string;
}
function UserPanel() {
const [count, setCount] = useState(0); // number
const [user, setUser] = useState<User | null>(null);
const [users, setUsers] = useState<User[]>([]);
return <button onClick={() => setCount(value => value + 1)}>{count}</button>;
}
// 显式元组返回类型,避免被推断为元素联合类型的数组
function useValue<T>(initialValue: T): [T, Dispatch<SetStateAction<T>>] {
return useState(initialValue);
}
Dispatch<SetStateAction<T>> 同时允许传入新值和 (previous: T) => T 更新函数。在 .tsx 中声明泛型箭头函数时,用 <T,> 避免被解析成 JSX。
Context
用 null 表达尚未提供 Context 的情况,通过自定义 Hook 校验并缩小类型:
import { createContext, useContext } from 'react';
interface ThemeContextValue {
theme: 'light' | 'dark';
toggleTheme: () => void;
}
const ThemeContext = createContext<ThemeContextValue | null>(null);
function useTheme(): ThemeContextValue {
const context = useContext(ThemeContext);
if (context === null) {
throw new Error('useTheme must be used within ThemeProvider');
}
return context;
}
Provider 提供的值需要满足 ThemeContextValue。集中在 Hook 中检查后,调用方无需重复处理空值,也无需用断言掩盖 Provider 缺失的问题。