作为参数传入的 useRef 需要添加到依赖项中吗?
从下面两个问题,我了解到useRef
不需要添加更新依赖。
我查看的相关问题:
但是当 useRef
用作props
、eslint
总是警告 hook
缺少依赖项?
import { useCallback, useEffect, useRef } from 'react';
const One = ({ refEl }) => {
const clickHandler = useCallback(e => {
refEl.current = 1111;
}, []); //⚠️ React Hook useCallback has a missing dependency: 'refEl'. Either include it or remove the dependency array.
useEffect(() => {
refEl.current = 2222;
}, []); //⚠️ React Hook useCallback has a missing dependency: 'refEl'. Either include it or remove the dependency array.
return (
<div onClick={clickHandler} ref={refEl}>
One
</div>
);
};
function App() {
const el = useRef('');
return <One refEl={el} />;
}
export default App;
From the following two questions, I understand that useRef
does not need to add update dependencies.
Related questions I looked at:
But when useRef
is used as props
, eslint
always warns about hook
missing dependencies?
import { useCallback, useEffect, useRef } from 'react';
const One = ({ refEl }) => {
const clickHandler = useCallback(e => {
refEl.current = 1111;
}, []); //⚠️ React Hook useCallback has a missing dependency: 'refEl'. Either include it or remove the dependency array.
useEffect(() => {
refEl.current = 2222;
}, []); //⚠️ React Hook useCallback has a missing dependency: 'refEl'. Either include it or remove the dependency array.
return (
<div onClick={clickHandler} ref={refEl}>
One
</div>
);
};
function App() {
const el = useRef('');
return <One refEl={el} />;
}
export default App;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
eslint 无法判断 refEl 是一个 ref,因此它只会将其视为普通 prop,将 ref 传递给您应该使用 React.forwardRef 的功能组件
eslint can't tell that refEl is a ref so it will just consider it as an ordinary prop to pass a ref down to a functional component you should use React.forwardRef