Callback refs not trigger when ref value changes in React.

huangapple go评论124阅读模式
英文:

Callback refs not trigger when ref value changes in React

问题

I am using useCallback to observer ref callback value changes but I getting only one node printed in console. How I can observer ref value changes?

使用 useCallback 来观察 ref 回调值的变化,但我只在控制台打印一次节点。如何观察 ref 值的变化?

const myRef = useRef(null);

const refObserver = useCallback(node => {
  if (node) {
    console.log(node); // 只打印一次
  }
}, []);

return (
  <>
    <div ref={refCb => {
      myRef.current = refCb;
      refObserver(refCb);
    }}>
      Hello world!
    </div>

    <button onClick={() => {
      myRef.current.innerText = `${Math.random()}`;
    }}>
      Change text!
    </button>
  </>
);
英文:

I am using useCallback to observer ref callback value changes but I getting only one node printed in console. How I can observer ref value changes ?

  const myRef = useRef(null);

  const refObserver = useCallback(node =&gt; {
    if (node) {
      console.log(node); // print one time only 
    }
  }, []); 

  return (
    &lt;&gt;
       &lt;div ref={refCb =&gt; {
           myRef.current = refCb;
           refObserver(refCb);
       }}&gt;
          Hello world!
       &lt;/div&gt;

       &lt;button onClick={() =&gt; {
          myRef.current.innerText = `${Math.random()}`;
       }}&gt;
          Change text!
       &lt;/button&gt;
    &lt;/&gt;
  )

答案1

得分: 2

组件中没有任何东西会触发重新渲染,因此引用回调只在组件挂载或卸载时执行。

为了使用React的渲染周期,使用状态来代替直接修改DOM属性(例如`innerText`)。

const [text, setText] = useState("Hello world!");

const refObserver = (node) => {
  if (node) {
    console.log("[refObserver]", node);
  }
};

return (
  <>
    <div ref={refObserver}>{text}</div>

    <button type="button" onClick={() => setText(Math.random())}>
      Change text!
    </button>
  </>
);

<details>
<summary>英文:</summary>

Nothing in your component would trigger a re-render so the ref callback will only be executed when the component is mounted or unmounted.

Use state instead of directly mutating DOM properties (ie `innerText`) in order to use React&#39;s render cycle

```lang-jsx
const [text, setText] = useState(&quot;Hello world!&quot;);

const refObserver = (node) =&gt; {
  if (node) {
    console.log(&quot;[refObserver]&quot;, node);
  }
};

return (
  &lt;&gt;
    &lt;div ref={refObserver}&gt;{text}&lt;/div&gt;

    &lt;button type=&quot;button&quot; onClick={() =&gt; setText(Math.random())}&gt;
      Change text!
    &lt;/button&gt;
  &lt;/&gt;
);

Callback refs not trigger when ref value changes in React.

huangapple
  • 本文由 发表于 2023年5月30日 06:28:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76360641.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定