React + Ts

下载一个项目

  1. 第一种方式
  2. 示例:
  3. // 旧
  4. create-react-app my-app --typescript
  5. // 新
  6. create-react-app my-app --template typescript
  1. 第二种方式
  2. 示例:
  3. // 旧
  4. npx create-react-app my-app --typescript
  5. // 新
  6. npx create-react-app my-app --template typescript

结尾后缀.tsx | .ts 结尾的文件才可以写 ts 语法

.ts和.tsx
  • js->ts
  • jsx->tsx

.ts和.d.ts
  • .ts是普通文件
  • .d.ts是声明文件

React.FC
  • FC = Functional Component
  • SFC = Stateless Functional Component (已弃用)

typescript: 无法使用 JSX,除非提供了 “—jsx“ 标志

  1. 无法使用 JSX,除非提供了 “–jsx 标志
  2. 出现这个警告的原因是你的typescript的本地版本和你当前项目的版本不一致,请将本地的ts版本更新至项目需要的版本
  3. cnpm install -g typescript@x.x.x
  4. cnpm install -S typescript@本地的版本(4.3.2

解决方案

  1. 1. 不用管, 就是标红就标红,反正也不会报错, 你就这么写就ok(.tsx结尾)
  2. 2. 把你所有的 .tsx 为后缀的文件,全部都改成 .ts 结尾的文件(.ts结尾)
  3. 3. 修改 tsconfig.js 中的 jsx: 'react'
  4. 但是这种的问题就是你每次重启他都会给你重新改成 react-jsx, 所以需要你每次重启之后都需要去改(.tsx结尾)
  5. 4. 可以选择当前的项目 ts 版本和本地的一致 找一个 .tsx 文件的地方,点击右下角的 ts 版本号,选择版本号,选择当前 vs 的版本号相等的版本即可

tsconfig.json项目配置:

  1. {
  2. "compilerOptions": { // 编译选择
  3. "target": "es5", // 指定ECMAScript目标版本。允许的值为“es3”、“es5”、“es6”、“es2015”、“es2016”、“es2017”、“es2018”或“esnext”。
  4. "lib": [ // 指定要包含在编译中的库文件。
  5. "dom",
  6. "dom.iterable",
  7. "esnext"
  8. ],
  9. "allowJs": true, // 允许编译javascript文件。
  10. "skipLibCheck": true, // 跳过声明文件的类型检查
  11. "esModuleInterop": true, // 为运行时babel生态系统兼容性提供“……importstar”和“……importdefault”帮助,并为类型系统兼容性启用“——allowSyntheticDefaultImports”。
  12. "allowSyntheticDefaultImports": true, // 允许从没有默认导出的模块进行默认导入。这并不影响代码发出,只影响类型查询。
  13. "strict": true, // 启用所有严格的类型检查选项。
  14. "forceConsistentCasingInFileNames": true, // 不允许对同一文件使用不一致大小写的引用。
  15. "module": "esnext", // 指定模块代码生成:“none”、“commonjs”、“amd”、“system”、“umd”、“es2015”或“esnext”。
  16. "moduleResolution": "node", // 指定模块解析策略:“node”(node)或“classic”
  17. "resolveJsonModule": true, // 包含导入的模块。json的扩展。
  18. "isolatedModules": true, // 无条件地为未解决的文件发出导入。
  19. "noEmit": true, // 不要发出输出。
  20. "jsx": "preserve" // 指定JSX代码生成:'preserve'、'react'或' reactive -native'。
  21. },
  22. "include": [ // 包含目录
  23. "src"
  24. ]
  25. }

下载一个声明文件(.d.ts)结尾的文件

  1. cnpm i -S @types/包名
  2. cnpm i -S react-router-dom @types/react-router-dom

可以把公用的接口进行封装出去,在一个文件中

  1. 示例:
  2. // 路由接口
  3. export interface PropsFace{
  4. path?: string,
  5. component?: any,
  6. from?: string,
  7. to?: string,
  8. children?: PropsFace[]
  9. }

断言

  1. 示例:
  2. to: (to={(item.to as string)})
  3. (<string>item.to) // 不允许在 react 使用
  4. <Redirect key={index} from={item.from} to={(item.to as string)} />;

FC

  1. 示例:
  2. 创建函数式组件的写法
  3. import { FC } from 'react';
  4. const 函数名:FC = () => {
  5. }

继承路由接口

  1. 示例:
  2. import { RouteComponentProps } from 'react-router-dom';
  3. interface IProps extends RouteComponentProps{
  4. routes: Array<PropsFace>
  5. }