你不需要成为 TS 专家,但必须掌握以下常见写法:
1. 基础类型与接口
// 基本类型
let name: string = 'React';
let age: number = 18;
let isActive: boolean = true;
let arr: number[] = [1, 2, 3];
let tuple: [string, number] = ['foo', 42];
// 接口(用于对象形状)
interface User {
id: number;
name: string;
email?: string; // 可选属性
readonly createdAt: Date; // 只读
}
// 类型别名(联合类型、复杂组合)
type Status = 'idle' | 'loading' | 'success' | 'error';
type ID = string | number;
2. 函数类型定义
// 普通函数
function add(a: number, b: number): number {
return a + b;
}
// 箭头函数(常用于 React 组件)
const greet = (name: string): void => {
console.log(`Hello ${name}`);
};
// 回调函数类型
function fetchData(callback: (data: User) => void) {
// ...
}
3. React 组件中常用类型
// 函数组件 Props 类型
interface ButtonProps {
label: string;
onClick: () => void;
disabled?: boolean;
}
const Button: React.FC<ButtonProps> = ({ label, onClick, disabled = false }) => {
return <button onClick={onClick} disabled={disabled}>{label}</button>;
};
// 或者不用 React.FC(更推荐,因为 React.FC 隐式包含 children)
const Button = ({ label, onClick, disabled = false }: ButtonProps) => {
// ...
};
// useState 类型推导通常自动,但复杂类型需显式
const [user, setUser] = useState<User | null>(null);
// useRef 用于 DOM 元素
const inputRef = useRef<HTMLInputElement>(null);
// 事件处理类型
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
console.log(e.target.value);
};
const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
e.preventDefault();
};
二、搭建项目(Vite + React + TS)
推荐使用 Vite(比 Create React App 更快,更现代)。
# 创建项目(选择 React + TypeScript)
npm create vite@latest my-react-app -- --template react-ts
cd my-react-app
npm install
npm run dev
项目结构建议(中小型项目):
src/
├── components/ # 通用组件(Button, Card等)
├── pages/ # 页面级组件(Home, About等)
├── hooks/ # 自定义 Hooks
├── services/ # API 调用
├── store/ # 状态管理(Redux/Zustand)
├── types/ # 全局 TS 类型定义
├── utils/ # 工具函数
├── App.tsx
├── main.tsx
└── index.css
三、核心 Hooks 实战
1. useState -- 管理简单状态
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState<number>(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>+1</button>
</div>
);
}
2. useEffect -- 处理副作用(替代生命周期)
import { useState, useEffect } from 'react';
function UserProfile({ userId }: { userId: string }) {
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
// 相当于 mounted + userId 变化时更新
let isMounted = true;
fetch(`/api/users/${userId}`)
.then(res => res.json())
.then(data => {
if (isMounted) setUser(data);
})
.finally(() => setLoading(false));
// 清理函数(相当于 beforeDestroy)
return () => { isMounted = false; };
}, [userId]); // 依赖数组:userId 变化时重新执行
if (loading) return <div>Loading...</div>;
return <div>{user?.name}</div>;
}
3、useCallback & useMemo -- 性能优化
// useMemo 缓存计算结果(类似 computed)
const expensiveValue = useMemo(() => {
return someHeavyComputation(data);
}, [data]);
// useCallback 缓存函数引用,避免子组件不必要的重渲染
const handleSave = useCallback(() => {
saveData(data);
}, [data]);
4、useRef -- 获取 DOM 或存储可变值(不触发重渲染)
function AutoFocusInput() {
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
inputRef.current?.focus(); // 自动聚焦
}, []);
return <input ref={inputRef} type="text" />;
}