REACT-在 React 项目中使用 TS
1. 使用规范参考
TS学习和在react中的应用
React 项目中使用 TS说明
React + TS 实践
类型化React TS 中的 Event Handler事件处理函数中的e
REACT-@reduxjs/toolkit+react-redux+redux-persist状态管理
让 create-react-app 支持自动使用 CSS Modules
使用 craco 配置基于 create-react-app 的开发环境
2. 补充
2.1 tsconfig.json 配置
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react",
"suppressImplicitAnyIndexErrors": true,
"baseUrl": "./",
"paths": {
"@/*":["src/*"],
"@assets/*":["src/assets/*"]
}
},
"include": [
"src"
],
}
2.2 重置样式和样式引入顺序
使用 reset-css 初始化浏览器css样式
安装依赖 npm i reset-css
引入依赖reset-css样式和样式的引入顺序
2.3 打包配置中引入node模块报错
比如引入 const path = require(‘path’);会报错
解决:安装说明文档模块来解决
npm i -D @types/node
2.4 绑定元素’children’隐式具有’any’类型
如何修复绑定元素’children’隐式具有’any’ type
import React, { ReactNode } from 'react'
<AuthCom>
<home />
</AuthCom>
interface AuthComProps {
children: ReactNode
}
//路由拦截
//需要定义整个props的类型
function AuthCom({children}:AuthComProps){//props.children
const isLogin = window.localStorage.getItem('token');
return isLogin?children:<Redirect to="/login"/>
}
2.5 No index signature with a parameter of type ‘string‘ was found on type ‘XXX‘
原因是key的值并不一定是对象的类中的字段名,要么放开ts限制如方式一,要么规范key的类型
No index signature with a parameter of type ‘string‘ was found on type ‘XXX‘
解决:在【tsconfig.json】文件中,【compilerOptions】节点下,配置
"suppressImplicitAnyIndexErrors": true
2.5 无法使用 JSX,除非提供了 “–jsx” 标志。
解决:在【tsconfig.json】文件中,【compilerOptions】节点下,配置
"jsx": "react",
2.6 @/地址关联失败
2.6.1 tsconfig.json
在【tsconfig.json】文件中,【compilerOptions】节点下,配置
"baseUrl": "./",
"paths": {
"@/*":[
"src/*"
]
}
2.6.2 craco.config.js
//对webpack配置别名
const path = require('path')
const resolve = (dir) => path.resolve(__dirname, dir)
module.exports = {
// webpack 配置
webpack: {
// 配置别名
alias: {
// 约定:使用 @ 表示 src 文件所在路径
'@': resolve('src')
},
},
}
2.7 Unexpected string concatenation of literals意外的文本字符串串联
解决:ESLint推荐用ES6方法来拼接字符串,而不能使用加号,需要使用模板字符串。
`userName=${userName}