1.安装
npm install --save react-router-dom
安装完成
新建两个页面并导出
app.js
import Nav from './components/Nav'
import Home from './components/Home'
import { Link, Route, Switch } from 'react-router-dom'
function App() {
return (
<div>
<div>
<p><Link to='/home'>home</Link></p>
<p><Link to='/nav'>nav</Link></p>
</div>
<div>
{/* <p><Route exact component={Home} path='/home'></Route></p> */}
{/* <p><Route exact component={Nav} path='/nav'></Route></p> */}
</div>
<hr />
<div>
<Switch>
<Route exact component={Home} path='/home'></Route>
<Route exact component={Home} path='/'></Route>
<Route exact component={Nav} path='/nav'></Route>
<Route exact component={Nav} path='/nav'></Route>
<Route exact component={Nav} path='/nav'></Route>
</Switch>
</div>
</div>
);
}
export default App;
index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { HashRouter } from 'react-router-dom'
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<HashRouter><App props="props" /></HashRouter>
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
‘Switch’ is not defined报错
原因版本过高
解决方法:卸载重装
npm uninstall react-router-dom
npm install react-router-dom@5