We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
这篇文章介绍 react-router-dom路由的几种跳转方式
示例中版本要求:react-router-dom 5.x
Link
适用场景:点击菜单跳转
使用 Link 组件方式跳转相当于点击 <a />标签方式跳转,因为Link 组件会渲染成<a href="/home">首页</a>
<a />
<a href="/home">首页</a>
代码示例:
import { BrowserRouter as Router,Link} from 'react-router-dom'; ... render(){ return ( <Router> <ul> <li> <Link to="/home">首页</Link> </li> <li> <Link to="/order">订单</Link> </li> </ul> </Router> ) } ...
Redirect
适用场景:重定向跳转,如登录后跳转
import { Redirect } from 'react-router-dom'; ... render(){ if (isLogin){ return <Redirect to='/home' />; }else{ return <Redirect to='/login' />; } } ...
withRouter
适用场景:通过 js 手动跳转
js
withRouter 能够将路由信息的match、location、history通过 props的方式传递给当前包装的组件
match
location
history
props
import { withRouter } from 'react-router-dom'; class demoComp extends React.Component{ constructor(props) { super(props); } goToHomePage = ()=>{ this.props.history.push('/home') } render() { return ( <button onClick={this.goToHomePage}>跳转首页</button> ) } } export default withRouter(demoComp)
--完--
The text was updated successfully, but these errors were encountered:
No branches or pull requests
前言
这篇文章介绍 react-router-dom路由的几种跳转方式
使用路由的
Link
组件方式跳转适用场景:点击菜单跳转
使用
Link
组件方式跳转相当于点击<a />
标签方式跳转,因为Link
组件会渲染成<a href="/home">首页</a>
代码示例:
使用路由
Redirect
组件方式跳转适用场景:重定向跳转,如登录后跳转
代码示例:
使用路由
withRouter
高级组件方式跳转适用场景:通过
js
手动跳转withRouter
能够将路由信息的match
、location
、history
通过props
的方式传递给当前包装的组件代码示例:
--完--
The text was updated successfully, but these errors were encountered: