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" />;
}
相关推荐
m0_50272495几秒前
vue3生成pdf
前端·javascript·vue.js·pdf
@不误正业2 分钟前
2026-05-16-多Agent协作框架深度实战-从ReAct到Plan-and-Execute全架构演进
前端·react.js·架构
我命由我123452 分钟前
PHP - PHP 简易 Web 服务器、基础接口开发
服务器·开发语言·前端·php·intellij-idea·idea·intellij idea
Reload.3 分钟前
CZ航司,shopping JS逆向 acw_sc__v2
开发语言·javascript·python·网络爬虫·ecmascript
咖喱o4 分钟前
IPv6
服务器·前端·网络
海上彼尚5 分钟前
Nodejs也能写Agent - 6.基础篇 - Agent
前端·人工智能·后端·node.js
2501_940041749 分钟前
纯前端实战:5个高复杂度业务与交互场景
前端
renke336413 分钟前
写给前端的 CANN-torchtitan-npu:昇腾PyTorch Titan适配到底是啥?
前端·人工智能·pytorch·cann
Richown13 分钟前
数据库优化:MySQL索引与查询优化
区块链·react
lihaozecq15 分钟前
Agent 开发的 skills 机制设计 - 渐进式披露
前端·agent·ai编程