官网:
react-router官网:https://reacttraining.com/react-router/web/guides/quick-start
使用:
这个官网文档比较干净简洁,写的很清楚的,所以我直接抄的(吐槽百度竟然首页没有,我用谷歌搜到的):
1、脚手架见一个项目:
npm install -g create-react-app create-react-app demo-app cd demo-app
2、安装react-router
npm install react-router-dom
3、基础使用demo:
import React from "react"; import { BrowserRouter as Router, Route, Link } from "react-router-dom"; function Index() { return <h2>Home</h2>; } function About() { return <h2>About</h2>; } function Users() { return <h2>Users</h2>; } function AppRouter() { return ( <Router> <div> <nav> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/about/">About</Link> </li> <li> <Link to="/users/">Users</Link> </li> </ul> </nav> <Route path="/" exact component={Index} /> <Route path="/about/" component={About} /> <Route path="/users/" component={Users} /> </div> </Router> ); } export default AppRouter;
4、嵌套用法:
import React from "react"; import { BrowserRouter as Router, Route, Link } from "react-router-dom"; function App() { return ( <Router> <div> <Header /> <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> <Route path="/topics" component={Topics} /> </div> </Router> ); } function Home() { return <h2>Home</h2>; } function About() { return <h2>About</h2>; } function Topic({ match }) { return <h3>Requested Param: {match.params.id}</h3>; } function Topics({ match }) { return ( <div> <h2>Topics</h2> <ul> <li> <Link to={`${match.url}/components`}>Components</Link> </li> <li> <Link to={`${match.url}/props-v-state`}>Props v. State</Link> </li> </ul> <Route path={`${match.path}/:id`} component={Topic} /> <Route exact path={match.path} render={() => <h3>Please select a topic.</h3>} /> </div> ); } function Header() { return ( <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/about">About</Link> </li> <li> <Link to="/topics">Topics</Link> </li> </ul> ); } export default App;