Skip to content
New issue

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 路由跳转方式 #31

Open
huangshuwei opened this issue Sep 27, 2019 · 0 comments
Open

react 路由跳转方式 #31

huangshuwei opened this issue Sep 27, 2019 · 0 comments
Labels
react react

Comments

@huangshuwei
Copy link
Owner

huangshuwei commented Sep 27, 2019

前言

这篇文章介绍 react-router-dom路由的几种跳转方式

示例中版本要求:react-router-dom 5.x

使用路由的 Link组件方式跳转

适用场景:点击菜单跳转

使用 Link 组件方式跳转相当于点击 <a />标签方式跳转,因为Link 组件会渲染成<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 手动跳转

withRouter 能够将路由信息的matchlocationhistory通过 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)

--完--

@huangshuwei huangshuwei added the react react label Sep 27, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
react react
Projects
None yet
Development

No branches or pull requests

1 participant