reactjs - 在 react-router 中使用 useRef 时,useRef.current 总是返回 undefined
问题描述
我正在尝试通过使用useRef钩子创建一个 ref 并将这个 ref 添加到 react-router Link。然后在useEffect挂钩内,我试图访问我的 ref 的current属性,但它始终是undefined。我在自定义组件或常见 html 元素的多个场合中以相同的方式使用useRef并且它始终有效。关于为什么它不适用于Link的任何想法?
import React, { useEffect, useRef } from 'react';
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types';
const MyComponent = ({ code, getCode }) => {
const linkRef = useRef();
useEffect(() => {
const { current } = linkRef || {};
if (linkRef !== undefined && current) {
console.log(current); // current is always undefined and it shouldn't
console.log(code);
}
}, [code, linkRef]);
return (
<div>
<Link
ref={linkRef}
to={{
pathname: '/enter-code',
query: { code },
}}
>
{'Link'}
</Link>
<button onClick={() => getCode()} type="button">
{'Get Code'}
</button>
</div>
);
};
MyComponent.propTypes = {
code: PropTypes.string,
getCode: PropTypes.func,
};
export default MyComponent;
我在用:
"react": "^16.12.0"
"react-router-dom": "^5.1.2"
解决方案
您不能使用单击链接。
正如打字稿错误所说,链接组件不能作为简单的锚标记单击。对此有两种建议的解决方案。
在 useRef 中将 Link 更改为并使用 HTMLAnchorElement 类型。
或者如果你想继续使用 react-router-dom 中的 Link 组件,你可以访问 link 组件的 props。您可以访问链接的“to”,但请确保仅在“to”道具中指定了直接 URL。
if (linkRef !== undefined && current) {
window.location.assign(linkRef.current.props.to.toString()); // redirect to the to prop on Link component }
推荐阅读
- java - 想填写setRoaming方法
- python - Python,Tkinter:将字符串评估为具有相同名称的对象,以便可以使用属性
- ruby-on-rails - Rails 测试作业并引发错误(如果有)
- firebase - 如何从 firebase 检索 url 并将其显示为 react native 中的可点击链接?
- visual-studio-code - 如何使VSCode中2个面板之间的边框永久可见?
- python - python文件路径未定义名称错误
- msal - MSAL-React 在应用程序中动态切换用户流
- python - 基于多列的熊猫数据框分组和百分比
- java - 按列表中的多个枚举值对对象列表进行分组
- html - 如何使用 CSS 在输入焦点上显示 div?