npm add react-router-dom并引入模块后编写路由,却报错: A <Route> is only ever to be used as the child of <Routes>。这是因为react-router-dom 6.0.2 高版本的router写法改变。如果想要遵从以前的写法,也可以修改版本依赖为低版本如^4.2.2。如果想适应新版本的写法,解决方法如下。
无论高低版本,src 下 index.js中引入BrowserRouter并包裹App:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter } from 'react-router-dom';
ReactDOM.render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>,
document.getElementById('root')
);
旧的低版本路由写法——子引入Link和Route,Route外不需要Routes包裹:
import React from 'react';
import { Link, Route } from 'react-router-dom'
import Home from './component/Home'
import About from './component/About'
export default class App extends React.Component {
render() {
return (
<div>
<div className="list-group">
{/* 编写路由链接 导航区的a标签改为Link标签*/}
<Link className="list-group-item" to="/about">显示About</Link>
<br />
<Link className="list-group-item" to="/home">显示Home</Link>
</div>
<div className="panel">
<div className="panel-body">
{/* 注册路由 展示区写Route标签进行路由的匹配*/}
<Route path="/about"component={About} />
<Route path="/home"component={Home} />
</div>
</div>
</div>
)
}
}
新的高版本路由写法——除了Link和Route还要引入Routes,包裹在Route外。注意element处的写法与之前component不同:
import React from 'react';
import { Link, Routes, Route } from 'react-router-dom'
import Home from './component/Home'
import About from './component/About'
export default class App extends React.Component {
render() {
return (
<div>
{/* 编写路由链接 */}
<div className="list-group">
<Link className="list-group-item" to="/about">显示About</Link>
<br />
<Link className="list-group-item" to="/home">显示Home</Link>
</div>
<div className="panel">
<div className="panel-body">
{/* 注册路由 */}
<Routes>
<Route path="/about" element={<About />} />
<Route path="/home" element={<Home />} />
</Routes>
</div>
</div>
</div>
)
}
}