【REACT-在 React 项目中使用 TS】

文章详细列举了在React项目中集成和使用TypeScript时可能遇到的问题及解决方案,包括tsconfig.json配置、样式重置、引入node模块报错、元素children类型错误、索引签名缺失、JSX使用问题以及路径别名配置等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值