react如何引用ts
在 React 中引用 TypeScript(TS)
要在 React 项目中引用 TypeScript,可以通过以下步骤完成配置和开发:
使用 Create React App 创建 TypeScript 项目
运行以下命令直接创建一个支持 TypeScript 的 React 项目:
npx create-react-app my-app --template typescript
这将自动配置 TypeScript 所需的依赖和基本设置。
手动添加 TypeScript 到现有项目
如果已有 React 项目,可以通过以下方式添加 TypeScript:
npm install --save typescript @types/node @types/react @types/react-dom @types/jest
然后重命名所有 .js 文件为 .tsx(用于 React 组件)或 .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 组件
创建一个 .tsx 文件并编写带有类型定义的组件:
import React from 'react';
interface Props {
name: string;
age?: number;
}
const MyComponent: React.FC<Props> = ({ name, age }) => {
return (
<div>
<p>Name: {name}</p>
{age && <p>Age: {age}</p>}
</div>
);
};
export default MyComponent;
类型化 Hooks
在使用 React Hooks 时也可以应用 TypeScript 类型:
const [count, setCount] = useState<number>(0);
const [user, setUser] = useState<{name: string, age: number} | null>(null);
处理事件类型
为事件处理函数添加正确的类型:
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
console.log(e.target.value);
};
通过以上方法,可以在 React 项目中顺利引用和使用 TypeScript,获得类型安全和更好的开发体验。







