当前位置: 首页 > 工具软件 > app-version > 使用案例 >

create-react-app 支持typescript

方夜洛
2023-12-01

文章参考

  1. Create React App 中文文档 ----添加 TypeScript
  2. react typescript

使用create-react-app 创建支持typescript语法项目

  1. 使用--scripts-version=react-scripts-ts,已过时,官方不推荐使用了
create-react-app my-app --scripts-version=react-scripts-ts
  1. 使用--template typescript创建
create-react-app my-react-ts-app --template typescript

手动创建依赖库,创建支持typescript语法项目

创建一个支持typescript的项目

$ npx create-react-app my-app --typescript

或者

$ yarn create react-app my-app --typescript

将 TypeScript 添加到 Create React App 项目

$ npm install --save typescript @types/node @types/react @types/react-dom @types/jest

或者

$ yarn add typescript @types/node @types/react @types/react-dom @types/jest

React 支持JSX 语法

Component泛型类

class Component<P, S> {
    readonly props: Readonly<{ children?: ReactNode }> & Readonly<P>;
    state: Readonly<S>;
}
  1. P 代表 Props 的类型, S 代表 State 的类型
  2. React 的类型定义文件 node_modules/@types/react/index.d.ts

例子

 
import * as React from 'react';
// 定义好 props 的字段
interface IProps {
  color: string,
  size?: string,
}

// 定义好 state 的字段
interface IState {
  count: number,
}
class App extends React.Component<IProps, IState> {
  public state = {
    count: 1,
  }
  public render () {
    return (
      <div>Hello world</div>
    )
  }
}

事件处理

常用 Event 事件对象类型:

  • ClipboardEvent<T = Element> 剪贴板事件对象
  • DragEvent<T = Element> 拖拽事件对象
  • ChangeEvent<T = Element> Change 事件对象
  • KeyboardEvent<T = Element> 键盘事件对象
  • MouseEvent<T = Element> 鼠标事件对象
  • TouchEvent<T = Element> 触摸事件对象
  • WheelEvent<T = Element> 滚轮事件对象
  • AnimationEvent<T = Element> 动画事件对象
  • TransitionEvent<T = Element> 过渡事件对象
 类似资料: