React Router 4.0中文快速入门

时间:2023-03-09 19:47:51
React Router 4.0中文快速入门
 import React from 'react'
import {
BrowserRouter as Router,
Route,
Link
} from 'react-router-dom' const Home = () => (
<div>
<h2>Home</h2>
</div>
) const About = (props) => {
let goto=function(){
console.log(props);
let { history } = props;
history.push('/topics'); //编程式跳转,注意使用prop来读取history
}
return (
<div>
<h2><button onClick={goto}>about</button></h2>
</div>
) } const Topic = ({ match }) => (
<div>
<h3>{match.params.topicId}</h3>
</div>
) const Topics = ({ match }) => (
<div>
<h2>Topics</h2>
<ul>
<li>
<Link to={`${match.url}/rendering`}>
Rendering with React:
</Link>
</li>
<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.url}/:topicId`} component={Topic}/>
<Route exact path={match.url} render={() => (
<h3>Please select a topic.</h3>
)}/>
</div>
) const BasicExample = ({ match }) => (
<Router> //跳由容器
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/topics">Topics</Link></li> <li><Link to="/query/user?id=123&name=minooo">query1</Link></li>
<li><Link to={{pathname: '/query/user', search: '?id=456&name=minooo'}}>query2</Link></li>
</ul> <hr/> <Route exact path="/" component={Home}/> //表示点击Link里的to就自动把组件渲染 <Route>位置这里 exact表示精确匹配
<Route path="/about" component={About}/>
<Route path="/topics" component={Topics}/> <Route path='/query/user' render={({match, location}) => ( //render他component一样的用法,不过render不用再次渲染,比较高效
<div>
<p><About></About></p>
<p>query</p>
<p>match:{JSON.stringify(match)}</p>
<p>location:{JSON.stringify(location)}</p>
<p>id:{new URLSearchParams(location.search).get('id')}</p>
<p>name:{new URLSearchParams(location.search).get('name')}</p>
</div>
)} /> </div>
</Router>
)
export default BasicExample