react如何使用ts
使用 TypeScript 与 React 结合开发
在 React 项目中使用 TypeScript 可以增强类型安全性和开发体验。以下是具体实现方法:
创建支持 TypeScript 的 React 项目
通过官方脚手架工具直接生成 TypeScript 模板:
npx create-react-app my-app --template typescript
对于 Vite 项目:
npm create vite@latest my-app -- --template react-ts
组件类型定义
函数组件可以通过 React.FC 或直接标注类型:
interface Props {
title: string;
count?: number;
}
const MyComponent: React.FC<Props> = ({ title, count = 0 }) => (
<div>
<h1>{title}</h1>
<p>Count: {count}</p>
</div>
);
类组件写法:
interface State {
clicks: number;
}
class Counter extends React.Component<Props, State> {
state: State = { clicks: 0 };
handleClick = () => {
this.setState(prev => ({ clicks: prev.clicks + 1 }));
}
}
处理事件类型
表单事件处理示例:

const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
console.log(e.target.value);
};
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
};
Hooks 类型标注
常见 Hooks 的类型使用方式:
const [count, setCount] = useState<number>(0);
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
const timer = setTimeout(() => {}, 1000);
return () => clearTimeout(timer);
}, []);
类型扩展与复用
创建可复用的类型定义:
type User = {
id: string;
name: string;
email?: string;
};
interface ApiResponse<T> {
data: T;
status: number;
}
第三方库类型支持
安装包含类型的库:

npm install @types/react-router-dom
对于没有官方类型的库,可以声明自定义类型:
declare module 'untyped-library' {
export function someFunction(arg: string): void;
}
配置 tsconfig.json
推荐的基础配置:
{
"compilerOptions": {
"target": "ES6",
"lib": ["dom", "dom.iterable", "esnext"],
"jsx": "react-jsx",
"strict": true,
"esModuleInterop": true
}
}
常见问题解决
处理 children 属性:
interface LayoutProps {
children: React.ReactNode;
}
const Layout = ({ children }: LayoutProps) => <div>{children}</div>;
样式对象类型:
const styles: React.CSSProperties = {
padding: '1rem',
backgroundColor: '#f5f5f5'
};






