react如何引用ts
React 中引用 TypeScript 的方法
在 React 项目中引入 TypeScript 可以通过多种方式实现,以下是常见的方法:
使用 Create React App (CRA) 初始化 TypeScript 项目
通过官方提供的模板直接创建支持 TypeScript 的 React 项目:
npx create-react-app my-app --template typescript
这种方式会自动配置 TypeScript 相关的依赖和基础类型定义。
手动添加 TypeScript 到现有 React 项目
在已有 React 项目中安装 TypeScript 和相关类型定义:
npm install --save typescript @types/react @types/react-dom
创建或重命名文件为 .tsx 扩展名,React 组件文件应使用 .tsx 而不是 .ts。
配置 TypeScript
确保项目根目录有 tsconfig.json 文件,基本配置如下:
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": ["src"]
}
编写 TypeScript React 组件
示例组件代码:
import React, { useState } from 'react';
interface Props {
name: string;
age?: number;
}
const MyComponent: React.FC<Props> = ({ name, age = 18 }) => {
const [count, setCount] = useState<number>(0);
return (
<div>
<h1>Hello, {name}! Age: {age}</h1>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
export default MyComponent;
类型定义最佳实践
为组件 Props 和 State 定义明确的接口:
interface User {
id: number;
name: string;
email: string;
}
interface UserListProps {
users: User[];
onSelect: (user: User) => void;
}
处理第三方库
对于没有内置类型定义的库,可以安装社区维护的类型:
npm install --save-dev @types/library-name
如果类型定义不存在,可以创建 declare.d.ts 文件手动声明模块。
构建和运行
配置 package.json 脚本使用 TypeScript 编译器:
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
}






