You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Router TSX报错:'Routes'被当作类型使用而非值的问题求助

问题分析与解决

报错原因

这个错误的核心是React Router DOM的版本与类型定义不兼容,分为两种常见情况:

  • React Router DOM v6及以上版本自带TypeScript类型定义,无需额外安装@types/react-router-dom。如果项目同时装了v6+的react-router-dom和旧版@types/react-router-dom,两者类型定义冲突,导致TypeScript误将Routes识别为类型而非组件。
  • 若安装的是React Router DOM v5及以下版本,该版本根本没有Routes组件(对应组件是Switch),导入Routes会让TypeScript找不到正确的组件定义,从而抛出类型混淆的错误。

解决方案

方案1:适配v6+版本(推荐)

  1. 卸载过时的类型包:
npm uninstall @types/react-router-dom
# 或使用yarn
yarn remove @types/react-router-dom
  1. 确保react-router-dom为最新v6版本:
npm install react-router-dom@latest
# 或使用yarn
yarn add react-router-dom@latest

方案2:保留v5版本的适配

如果需要继续使用v5,替换组件并调整属性:

import { Route, Switch } from "react-router-dom";

const AppRoutes = () => {
    return (
        <Switch>
            <Route path="/" component={() => <span>Home Page</span>} />
        </Switch>
    );
};

export default AppRoutes;

额外检查

确认tsconfig.json的jsx配置正确,建议设置为:

{
  "compilerOptions": {
    "jsx": "react-jsx"
  }
}

内容的提问来源于stack exchange,提问作者Aditya Mistri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 17:02:02