1. 安装
npm install react-router-dom --save --dev
2. 新建 router.js
import React from 'react'; import {BrowserRouter as Router, Route, Switch} from 'react-router-dom'; import App from "../App"; import SH from "../views/stateHook"; const BasicRoute = () => ( <Router> <Switch> <Route path="/" component={App}/> <Route exact path="/index" component={SH}/> </Switch> </Router> ); export default BasicRoute;
这里使用 BrowserRouter 路由,因为该路由使用HTML5的history API(pushState, replaceState和popState),让页面的UI与URL同步。
Switch 这里是从上向下匹配,如果匹配到就不会向下匹配,exact是精确匹配
3. App.js
import './App.css'; function App() { return ( <div className="App"> <h1>这里是App.js</h1> </div> ); } export default App;
4. stateHook.js
import React, { useState } from "react"; export default function SH () { let [count, setCount] = useState(0) return <div style={{backgroundColor: 'gold', textAlign: 'center', padding: '50px'}}> { count } <div> <button type={"button"} onClick={() => setCount(count+1)}>count++</button> </div> </div> }
根路径:
/index
5. 组件内<Link> <NavLink>跳转路由
import { Link, NavLink } from "react-router-dom";
Link
<p><Link to='/test'>Link跳转到test</Link></p>
直接加上path, 可带参数 '/test?name=1'
<p><Link to= {{ pathname: '/test', search: '?name=1' }}>Link对象方式跳转到test</Link></p>
使用对象格式进行跳转,search后可带参数
NavLink
<p><NavLink to='/test'>NavLink跳转到test</NavLink></p> <p><NavLink to='/index' activeClassName="highlight">激活当前index路由</NavLink></p> <p><NavLink to='/index' activeStyle={{color: 'yellow'}}>激活当前index路由</NavLink></p>
该标签不仅可以跳转路由,更适用于激活当前链接
render() {
const isAct = () => {
console.log(Math.random() * 100 > 10)
return Math.random() * 100 > 10
}
return (
<p><NavLink to='/test' isActive={ isAct } activeStyle={{ color: 'yellow' }}>跳转至index</NavLink></p>
)
}
上述可以用函数控制是否激活,该方法只适用于class创建的组件
6. 事件内跳转路由
jump () {
this.props.history.push('/index?id=000')
// 对象方式跳转
this.props.history.push({pathname: '/index', search: '?id=000'})
}
<button type={'button'} onClick={() => {this.jump()}}>事件内跳转路由</button>
7. 路由嵌套
<Route path="/home" component={Home} /> <Route path="/home/pagea" component={SH} />
/home
/home/pagea
切记 在嵌套路由时不要使用Switch exact