reactjs - 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();
解决方案
正如打字稿错误所说,Link
组件不能像锚一样简单地单击。对此有两种建议的解决方案。
将链接更改为
<a href="...">
并HTMLAnchorElement
使用useRef
.或者,如果您想继续使用
Link
来自 的组件react-router-dom
,您可以访问props
链接组件的 。
if (myLink.current) {
window.location.assign(myLink.current.props.to.toString()); // redirect to the to prop on Link component
}
推荐阅读
- pybind11 - 将存储 long 的 pybind11::object 转换为 ssize_t
- c# - 包含中的 where 语句不过滤
- java - catch (Exception e) {} vs finally {}
- python - 如何在 Python 中检索证券交易所的价格数据?
- python - Python正则表达式在包含单词的标签之间查找块
- r - 使用 mutate 和 pivot_longer 创建 gpa 变量
- assembly - 分支延迟:如果分支更改了分支延迟槽中的指令使用的值怎么办
- android - Android - 让活动覆盖在一切之上
- python - 如何编辑表单集
- aws-powershell - WriteS3-Object 指定的值具有无效的 CRLF 字符