这里主要讲解新旧版本的路由用法:npm i react-router-dom --save并引入模块后编写路由,却报错: 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 { NavLink, 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标签*/}
<ul>
<li>
<NavLink activeClassName="active" to="/about">显示About</NavLink>
</li>
<li>
<NavLink activeClassName="active" to="/home">显示Home</NavLink>
</li>
</ul>
</div>
<div className="panel">
<div className="panel-body">
{/* 注册路由 展示区写Route标签进行路由的匹配 Switch是为了一个path和component一一对应匹配*/}
<Switch>
<Route path="/about"component={About} />
<Route path="/home"component={Home} />
</Switch>
</div>
</div>
</div>
)
}
}
新的高版本路由写法——除了Link和Route还要引入Routes,包裹在Route外,并且Routes代替了旧版中的Switch实现精准匹配。注意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>
)
}
}