首页 > 解决方案 > 如何在功能组件内的功能上使用与 react-router 的链接相同的行为?

问题描述

我正在使用 React-router v5,我想使用与 Link 组件相同的行为

<form className="align-bottom d-flex align-baseline align-items-md-end form-inline float-right">
        
    ...
    <Button type="button" className={"align-center getStarted btn mx-0 "}
       onMouseDown={e => e.preventDefault()} onClick={signUpHandler}>
       <HeaderLink className={'excluded'}>Get started</HeaderLink>
    </Button>
    ...
       
</form>

我不想用链接包装开始按钮,因为我想检查网站是否是从小型设备访问的(然后不显示弹出窗口,但在 url 内)或桌面屏幕(然后只显示弹出窗口-向上)。

这是我到目前为止在单击“开始”按钮时尝试的登录:

const Header = () => {
    ...
    const signUpHandler = () => {
        const mql = window.matchMedia('(max-width: 900px)')
        if (mql.matches) {
            // The viewport is less than 670px
            window.location.href = "/sign-up";
            // <Redirect to='/login' />
        } else {
            // The viewport is wider than 670px
            toggleVisibility(!isVisible);
            changeIsLogIn(false)
            // changeIsLogIn(isLogIn => false)
        }
    }
   ...
}

因此,window.location.href = "/sign-up";我只想使用 react-router 的链接来重定向用户,而不是重新加载整个屏幕(在小屏幕上)。

任何帮助或建议将不胜感激,谢谢!

标签: reactjsreact-router-dom

解决方案


使用 useHistory() 钩子。

在这里你有一个很好的文档:

https://reactrouter.com/web/api/Hooks


推荐阅读