react-router简单使用方法实例
程序员文章站
2022-07-03 15:24:34
...
1.安装
npm i react --save
npm i react-router-dom --save
在之前看文档时,使用react-router用到NavLink时报:
Attempted import error: ‘NavLink’ is not exported from ‘react-router’.错误,后来查了一下react-router不支持,要安装react-router-dom ,它依赖react-router,安装后面一个就行了
2.在index.js文件中引用 BrowserRouter, 将 包裹起来以后用到路由时就不用了在每一个用到的地方加了。
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<App />,
document.getElementById('root')
);
serviceWorker.unregister();
跟改为:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { BrowserRouter} from 'react-router-dom';
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root')
);
serviceWorker.unregister();
3.在项目目录下建一个文件components用来存放组件
import React from 'react';
import { Route, Link, NavLink } from 'react-router-dom'; //NavLink和Link都是链接相当于a标签。 Link只有相应的结果,看不到状态,NavLink都可以
import Top from './components/Top.js';
import Index from './components/index.js';
import About from './components/about.js';
import './css/main.css'
function App() {
return (
<div>
<Top></Top>
<div>
<div className="left">
<ul>
<li><NavLink exact to="/">主页</NavLink></li> //exact 默认显示组件
<li><NavLink to="/about">关于</NavLink></li>
</ul>
</div>
<div className="right">
<Route exact path="/" component={Index}></Route>
<Route path="/about" component={About}></Route>
</div>
</div>
</div>
);
}
export default App;
App.js
import React, { Component } from 'react';
export default class top extends Component{
render () {
return (
<div>首页</div>
)
}
}
index.js
import React, { Component } from 'react';
export default class about extends Component{
render () {
return (
<div>
<ul>
<li>主页</li>
<li>产品</li>
<li>联系我们</li>
<li>个人中心</li>
</ul>
</div>
)
}
}
about.js
4.运行结果如下