首页 > 解决方案 > React TypeScript:使用引用链接

问题描述

如何将 useRef 与链接一起使用

import {Link} from 'react-router-dom';
const myLink = useRef<Link>(null);
...
myLink.current.click()
...

<Link to={{pathname: '/terms'}} id='myLink' ref={myLink} />

我得到的错误是Property 'click' does not exist on type 'Link<any>'.ts(2339)

我目前正在使用以下内容,但我想转到 useRef

    const myLink = document.getElementById('myLink');
    if (myLink) myLink.click();

标签: reactjstypescript

解决方案


正如打字稿错误所说,Link组件不能像锚一样简单地单击。对此有两种建议的解决方案。

  1. 将链接更改为<a href="...">HTMLAnchorElement使用useRef.

  2. 或者,如果您想继续使用Link来自 的组件react-router-dom,您可以访问props链接组件的 。

if (myLink.current) {
    window.location.assign(myLink.current.props.to.toString()); // redirect to the to prop on Link component
}

推荐阅读