作为参数传入的 useRef 需要添加到依赖项中吗?

发布于 2025-01-10 21:28:06 字数 1102 浏览 0 评论 0原文

从下面两个问题,我了解到useRef不需要添加更新依赖。

我查看的相关问题:

但是当 useRef 用作propseslint 总是警告 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

故人如初 2025-01-17 21:28:06

eslint 无法判断 refEl 是一个 ref,因此它只会将其视为普通 prop,将 ref 传递给您应该使用 React.forwardRef 的功能组件

import { useCallback, useEffect, useRef, forwardRef } from "react";

const One = forwardRef((props, ref) => {
  const clickHandler = useCallback((e) => {
    ref.current = 1111;
  }, [ref]);

  useEffect(() => {
    ref.current = 2222;
  }, [ref]);

  return (
    <div onClick={clickHandler} ref={ref}>
      One
    </div>
  );
});

function App() {
  const el = useRef("");
  return <One ref={el} />;
}

export default App;

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

import { useCallback, useEffect, useRef, forwardRef } from "react";

const One = forwardRef((props, ref) => {
  const clickHandler = useCallback((e) => {
    ref.current = 1111;
  }, [ref]);

  useEffect(() => {
    ref.current = 2222;
  }, [ref]);

  return (
    <div onClick={clickHandler} ref={ref}>
      One
    </div>
  );
});

function App() {
  const el = useRef("");
  return <One ref={el} />;
}

export default App;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文