TypeScript中的React开发

你不需要成为 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" />;
}
相关推荐
山河木马11 小时前
矩阵专题3-怎么创建投影矩阵(uProjectionMatrix)
javascript·webgl·计算机图形学
天蓝色的鱼鱼11 小时前
关于 CSS 你可能不知道的属性,但关键时刻很有用
前端·css
泯泷12 小时前
第 2 篇:设计第一套字节码:Opcode、Instruction 与 Constant Pool
前端·javascript·安全
妙码生花12 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(十五):优化细节、网络请求封装
前端·后端·ai编程
泯泷12 小时前
第 1 篇:从 1 + 2 开始:亲手写出第一台 JSVM
前端·javascript·安全
团团崽_七分甜12 小时前
Spring Boot 核心知识点总结
前端
lichenyang45313 小时前
从一个按钮开始,理解 ASCF 框架到底在做什么
前端
古夕13 小时前
第三方 SSO 接入实践:redirect_uri 编码、回调一致性与跨项目联调
前端·vue.js
朦胧之13 小时前
页面白屏卡住排查方法
前端·javascript
用户5936087414013 小时前
Playwright 黑魔法:用 ClipboardEvent 绕过 React 富文本编辑器
前端