1. 程式人生 > >React Router 4.0中文快速入門

React Router 4.0中文快速入門

arch ring ooo 組件 arc ret 自動 import export

 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中文快速入門