当前位置:首页 > React

typescript react 如何

2026-02-26 00:46:20React

使用 TypeScript 与 React 开发应用

TypeScript 与 React 结合可以提升代码的可维护性和类型安全性。以下是关键步骤和最佳实践:

初始化 React + TypeScript 项目

使用 create-react-app 快速搭建项目:

npx create-react-app my-app --template typescript

或使用 Vite(推荐):

npm create vite@latest my-app -- --template react-ts

定义组件 Props 和 State

使用 interfacetype 明确组件 Props 和 State 的类型:

interface ButtonProps {
  label: string;
  onClick: () => void;
  disabled?: boolean;
}

const Button: React.FC<ButtonProps> = ({ label, onClick, disabled }) => {
  return <button onClick={onClick} disabled={disabled}>{label}</button>;
};

处理事件类型

React 事件类型需使用泛型,如 React.MouseEvent

typescript react 如何

const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
  console.log(e.currentTarget.value);
};

使用 Hooks 的类型

useState 指定类型:

const [count, setCount] = useState<number>(0);

useReducer 定义类型:

type State = { count: number };
type Action = { type: 'increment' | 'decrement' };

const reducer = (state: State, action: Action): State => {
  switch (action.type) {
    case 'increment': return { count: state.count + 1 };
    case 'decrement': return { count: state.count - 1 };
    default: return state;
  }
};

类型化 Context API

创建类型安全的 Context:

typescript react 如何

interface ThemeContextType {
  theme: 'light' | 'dark';
  toggleTheme: () => void;
}

const ThemeContext = React.createContext<ThemeContextType | undefined>(undefined);

const useTheme = () => {
  const context = useContext(ThemeContext);
  if (!context) throw new Error('useTheme must be used within a ThemeProvider');
  return context;
};

处理第三方库类型

安装库的类型定义(如 @types/react-router-dom):

npm install --save-dev @types/react-router-dom

若库无类型,可手动声明:

declare module 'untyped-library' {
  export const someFunction: () => void;
}

配置 tsconfig.json

确保关键配置启用:

{
  "compilerOptions": {
    "jsx": "react-jsx",
    "strict": true,
    "esModuleInterop": true
  }
}

泛型组件示例

创建可复用的列表组件:

interface ListProps<T> {
  items: T[];
  renderItem: (item: T) => React.ReactNode;
}

const List = <T,>({ items, renderItem }: ListProps<T>) => (
  <ul>{items.map((item, index) => <li key={index}>{renderItem(item)}</li>)}</ul>
);

通过以上方法,可以高效地结合 TypeScript 和 React 开发类型安全的应用程序。

标签: typescriptreact
分享给朋友:

相关文章

如何优化react

如何优化react

优化 React 性能的方法 使用 React.memo 或 PureComponent 对于函数组件,使用 React.memo 进行记忆化,避免不必要的重新渲染。类组件可以使用 PureCompo…

react如何发音

react如何发音

React的发音 React的正确发音为 /riˈækt/,类似于“ree-akt”。以下是详细说明: 发音分解 第一个音节“Ree”发音类似英文单词“see”中的“ee”音。…

react如何打包

react如何打包

打包 React 项目的基本步骤 React 项目通常使用 create-react-app 或类似的脚手架工具创建,这些工具内置了打包功能。以下是打包 React 项目的详细方法: 安装依赖并构建…

react 如何操作cookie

react 如何操作cookie

安装依赖 在React项目中操作cookie通常需要第三方库的支持,推荐使用js-cookie。通过npm或yarn安装: npm install js-cookie # 或 yarn add js…

react如何引入echarts

react如何引入echarts

安装 ECharts 依赖 在 React 项目中安装 ECharts 核心库和 React 封装库: npm install echarts echarts-for-react 基础引入方式 创建…

react如何筛选数据

react如何筛选数据

筛选数据的方法 在React中筛选数据通常涉及对数组的操作,结合状态管理和渲染逻辑。以下是几种常见的实现方式: 使用数组的filter方法 通过JavaScript数组的filter方法筛选数据,并…