如何将 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();
最佳答案
正如 typescript 错误所说,Link
组件不能像anchor一样简单的点击。有两个建议的解决方案。
将链接更改为
<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
}
关于reactjs - react typescript : useRef to Link,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57934143/