react-router-dom中文文档,官方文档翻译1:快速开始,安装及示例
一直没有找到react-router-dom的中文文档,特此把学习过程记录一下,希望能够帮到大家
你可能需要先搭建一个react项目, 可以通过create-react-app来创建react项目
npm install -g create-react-app create-react-app demo-app cd demo-app
我们可以通过npm或者yarn来安装react-router-dom
npm install react-router-dom
在这个示例中,我们将通过<Router>来切换3个'page'组件
注意:我们通过 <Link to="/">
代替 <a href="/">
来进行路由跳转
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;
这个示例展示怎么嵌套路由,路由‘/topics’ 加载 Topics组件 , 在Topics组件中又定义了它的子路由 ,规则为'/topics/:id',:id代表一个可变的值,如在浏览器中输入'/topics/components',则在子路由组件中,可通过 props.match.params.id来获取'components'
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> //子路由规则为 topics/:id 子路由对应组件Topic <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;
下节介绍react-router-dom的基础组件
点赞(1)