React Router 4.0中文快速入门
Posted Yuri 前端什么狮子
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了React Router 4.0中文快速入门相关的知识,希望对你有一定的参考价值。
1 import React from ‘react‘ 2 import { 3 BrowserRouter as Router, 4 Route, 5 Link 6 } from ‘react-router-dom‘ 7 8 const Home = () => ( 9 <div> 10 <h2>Home</h2> 11 </div> 12 ) 13 14 const About = (props) => { 15 let goto=function(){ 16 console.log(props); 17 let { history } = props; 18 history.push(‘/topics‘); //编程式跳转,注意使用prop来读取history 19 } 20 return ( 21 <div> 22 <h2><button onClick={goto}>about</button></h2> 23 </div> 24 ) 25 26 } 27 28 const Topic = ({ match }) => ( 29 <div> 30 <h3>{match.params.topicId}</h3> 31 </div> 32 ) 33 34 const Topics = ({ match }) => ( 35 <div> 36 <h2>Topics</h2> 37 <ul> 38 <li> 39 <Link to={`${match.url}/rendering`}> 40 Rendering with React: 41 </Link> 42 </li> 43 <li> 44 <Link to={`${match.url}/components`}> 45 Components 46 </Link> 47 </li> 48 <li> 49 <Link to={`${match.url}/props-v-state`}> 50 Props v. State 51 </Link> 52 </li> 53 </ul> 54 55 <Route path={`${match.url}/:topicId`} component={Topic}/> 56 <Route exact path={match.url} render={() => ( 57 <h3>Please select a topic.</h3> 58 )}/> 59 </div> 60 ) 61 62 const BasicExample = ({ match }) => ( 63 <Router> //跳由容器 64 <div> 65 <ul> 66 <li><Link to="/">Home</Link></li> 67 <li><Link to="/about">About</Link></li> 68 <li><Link to="/topics">Topics</Link></li> 69 70 <li><Link to="/query/user?id=123&name=minooo">query1</Link></li> 71 <li><Link to={{pathname: ‘/query/user‘, search: ‘?id=456&name=minooo‘}}>query2</Link></li> 72 </ul> 73 74 75 76 <hr/> 77 78 <Route exact path="/" component={Home}/> //表示点击Link里的to就自动把组件渲染 <Route>位置这里 exact表示精确匹配 79 <Route path="/about" component={About}/> 80 <Route path="/topics" component={Topics}/> 81 82 <Route path=‘/query/user‘ render={({match, location}) => ( //render他component一样的用法,不过render不用再次渲染,比较高效 83 <div> 84 <p><About></About></p> 85 <p>query</p> 86 <p>match:{JSON.stringify(match)}</p> 87 <p>location:{JSON.stringify(location)}</p> 88 <p>id:{new URLSearchParams(location.search).get(‘id‘)}</p> 89 <p>name:{new URLSearchParams(location.search).get(‘name‘)}</p> 90 </div> 91 )} /> 92 93 </div> 94 </Router> 95 ) 96 export default BasicExample
以上是关于React Router 4.0中文快速入门的主要内容,如果未能解决你的问题,请参考以下文章
react-router 4.0、react-router-dom 和 react-router-redux 有啥区别?