首页 > 解决方案 > 如何重定向到函数中的另一个组件?

问题描述

在我的 app.tsx 中,我有这个带有 react-router-dom 的结构:

<BrowserRouter>
                <Switch>
                    <Route path={"/login"} component={Login}/>
                    <Route path={"/home"} component={HomeScreen}/>
                    <Route path={"/user"} component={UserMenu}/>
                    <Route path={"/profile"} component={ProfileScreen}/>

                    {<Redirect to={"/login"}/>}

                </Switch>
            </BrowserRouter>

在每个组件中,我想要一个允许我在它们之间移动的函数,例如,我尝试过 this.props.history.push () 但它对我不起作用,有什么想法吗?

标签: reactjs

解决方案


如果您正在使用功能组件,则可以使用 useHistory。

import React from 'react';
import { useHistory } from 'react-router-dom';

const Hello = () => {
  const history = useHistory();
  const handleClick = () => history.push('/route');
  
  return (
    <button type="button" onClick={handleClick}>
      Navigate
    </button>
  );
};

如果您使用的是类组件,则可以使用 withRouter:

import { withRouter } from 'react-router-dom'

class Hello extends React.Component {
  handleClick = (user) => {
      this.props.history.push('/route')
  }
  render() {
    return (
       <button type="button" onClick={this.handleClick}>
         Navigate
       </button>
    )
  }
}

export default withRouter(Hello)

推荐阅读