React + Ts
下载一个项目
第一种方式
示例:
// 旧
create-react-app my-app --typescript
// 新
create-react-app my-app --template typescript
第二种方式
示例:
// 旧
npx create-react-app my-app --typescript
// 新
npx create-react-app my-app --template typescript
结尾后缀.tsx | .ts 结尾的文件才可以写 ts 语法
.ts和.tsx
.ts和.d.ts
React.FC
- FC = Functional Component
- SFC = Stateless Functional Component (已弃用)
typescript: 无法使用 JSX,除非提供了 “—jsx“ 标志
无法使用 JSX,除非提供了 “–jsx” 标志
出现这个警告的原因是你的typescript的本地版本和你当前项目的版本不一致,请将本地的ts版本更新至项目需要的版本
cnpm install -g typescript@x.x.x
cnpm install -S typescript@本地的版本(4.3.2)
解决方案
1. 不用管, 就是标红就标红,反正也不会报错, 你就这么写就ok(.tsx结尾)
2. 把你所有的 .tsx 为后缀的文件,全部都改成 .ts 结尾的文件(.ts结尾)
3. 修改 tsconfig.js 中的 jsx: 'react',
但是这种的问题就是你每次重启他都会给你重新改成 react-jsx, 所以需要你每次重启之后都需要去改(.tsx结尾)
4. 可以选择当前的项目 ts 版本和本地的一致 找一个 .tsx 文件的地方,点击右下角的 ts 版本号,选择版本号,选择当前 vs 的版本号相等的版本即可
tsconfig.json项目配置:
{
"compilerOptions": { // 编译选择
"target": "es5", // 指定ECMAScript目标版本。允许的值为“es3”、“es5”、“es6”、“es2015”、“es2016”、“es2017”、“es2018”或“esnext”。
"lib": [ // 指定要包含在编译中的库文件。
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true, // 允许编译javascript文件。
"skipLibCheck": true, // 跳过声明文件的类型检查
"esModuleInterop": true, // 为运行时babel生态系统兼容性提供“……importstar”和“……importdefault”帮助,并为类型系统兼容性启用“——allowSyntheticDefaultImports”。
"allowSyntheticDefaultImports": true, // 允许从没有默认导出的模块进行默认导入。这并不影响代码发出,只影响类型查询。
"strict": true, // 启用所有严格的类型检查选项。
"forceConsistentCasingInFileNames": true, // 不允许对同一文件使用不一致大小写的引用。
"module": "esnext", // 指定模块代码生成:“none”、“commonjs”、“amd”、“system”、“umd”、“es2015”或“esnext”。
"moduleResolution": "node", // 指定模块解析策略:“node”(node)或“classic”
"resolveJsonModule": true, // 包含导入的模块。json的扩展。
"isolatedModules": true, // 无条件地为未解决的文件发出导入。
"noEmit": true, // 不要发出输出。
"jsx": "preserve" // 指定JSX代码生成:'preserve'、'react'或' reactive -native'。
},
"include": [ // 包含目录
"src"
]
}
下载一个声明文件(.d.ts)结尾的文件
cnpm i -S @types/包名
cnpm i -S react-router-dom @types/react-router-dom
可以把公用的接口进行封装出去,在一个文件中
示例:
// 路由接口
export interface PropsFace{
path?: string,
component?: any,
from?: string,
to?: string,
children?: PropsFace[]
}
断言
示例:
to: (to={(item.to as string)})
(<string>item.to) // 不允许在 react 使用
<Redirect key={index} from={item.from} to={(item.to as string)} />;
FC
示例:
创建函数式组件的写法
import { FC } from 'react';
const 函数名:FC = () => {
}
继承路由接口
示例:
import { RouteComponentProps } from 'react-router-dom';
interface IProps extends RouteComponentProps{
routes: Array<PropsFace>
}