[英]React TypeScript: useRef to Link
How to use useRef with Link 如何在链接中使用useRef
import {Link} from 'react-router-dom';
const myLink = useRef<Link>(null);
...
myLink.current.click()
...
<Link to={{pathname: '/terms'}} id='myLink' ref={myLink} />
the error I get is Property 'click' does not exist on type 'Link<any>'.ts(2339)
我得到的错误是
Property 'click' does not exist on type 'Link<any>'.ts(2339)
I'm currently using the below but i want to move to useRef 我目前正在使用下面但我想转向useRef
const myLink = document.getElementById('myLink');
if (myLink) myLink.click();
As the typescript error says, Link
component cannot be clicked as simply as anchor. 正如打字稿错误所说,
Link
组件不能像锚一样简单地点击。 There are two proposed solutions to this. 有两种建议的解决方案。
Change Link to <a href="...">
and use HTMLAnchorElement
type in the useRef
. 将链接更改为
<a href="...">
并在useRef
使用HTMLAnchorElement
类型。
Or if you want to stay using Link
component from react-router-dom
, you can access the props
of the link component. 或者,如果你想保持使用
Link
组件从react-router-dom
,你可以访问该props
的链接组件。
if (myLink.current) {
window.location.assign(myLink.current.props.to.toString()); // redirect to the to prop on Link component
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.