使用react-router配置Routes后点击任意链接均渲染PointAndClick组件问题
问题原因
- 核心错误在
App.tsx的模块导入逻辑:你导入DraggableGame组件时错误使用了PointAndClickGame的文件路径,导致两个导入指向同一个组件实例,无论路由匹配到哪条规则,最终渲染的都是PointAndClickGame组件。 - 若你使用的是
react-router v6及以上版本,还存在语法不兼容问题:v6要求所有Route必须嵌套在Routes组件内,且渲染的组件需要通过element属性传入,不能直接作为Route的子元素。
修复步骤
1. 修正导入路径
将App.tsx头部的导入语句替换为正确写法:
// 修正前的错误写法 // import DraggableGame from './PointAndClickGame'; // import PointAndClickGame from './PointAndClickGame'; // 修正后的写法 import DraggableGame from './DraggableGame'; import PointAndClickGame from './PointAndClickGame';
2. 适配react-router v6(可选,仅v6+版本需要执行)
如果你的react-router依赖版本为v6及以上,需要调整路由部分的代码以符合新语法规范:
// 首先导入Routes组件 import { BrowserRouter as Router, Link, Route, Routes } from "react-router-dom"; function App() { return ( <div className="App"> <Router> <Routes> <Route exact path='/' element={ <> <Link to="/pointAndClick">joc pointAndClick</Link><br/> <Link to="/draggable">joc draggable</Link> </> } /> <Route exact path="/pointAndClick" element={<PointAndClickGame/>} /> <Route exact path="/draggable" element={<DraggableGame/>} /> </Routes> </Router> </div> ); }
内容的提问来源于stack exchange,提问作者user14399919
相关产品推荐
相关产品推荐

