使用路由首先需要安装react-router-dom
随后引入react-router !!注意 首字母大写
import {BrowserRouter as Router,Route,link} from "react-router-dom"
1、根据网址自动判断页面
随后在app根标签内 !!注意 exact path 如果你的 "/"默认地址没有用exact path 遇到"/home"
会同时把 匹配为 "/"的页面和 "/home"的页面同时加载出来 "/"建议用exact path
exact path为严格匹配路由地址
function App() {
return (
<div className="App">
<div></div>
{/* <News/> */}
<Router>
<div>
<Route exact path="/" component={Home}></Route>
<Route path="/home" component={Home}></Route>
<Route path="/news" component={News}></Route>
<Route path="/list" component={List}></Route>
</div>
</Router>
</div>
);
}
component代表你的组件 组件需要先import引入在使用
2、按钮跳转 注意Link首字母大写
function App() {
return (
<div className="App">
<Router>
<div>
<Link to="/list">list</Link>
<br/>
<Link to="/home">home</Link>
<hr/>
<br/>
</div>
</Router>
</div>
);
}
这样就可以通过标签跳转页面
3 嵌套路由 要记住 path不加 exact会匹配 / 路由页面
和app.js的路由同理,
比如user用户页面 在组件component文件夹中新建一个user 的子组件文件夹
在user.js文件中引入这两个文件 和react-router
随后 就可以在render编写路由代码了
function App() {
return (
<div className="App">
<div></div>
{/* <News/> */}
<Router>
<div>
<Route exact path="/" component={Home}></Route>
<Route path="/user/xxx" component={xxx}></Route>
</div>
</Router>
</div>
);
}
另一种方式
<Router>
<div>
<Route exact path="/" component={Home}></Route>
<Route path={'${this.props.match.url}/xxx'} component={xxx}></Route>
</div>
</Router>
可以通过this.props.match.url获取当前的路由地址