英文:
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 => {
if (node) {
console.log(node); // print one time only
}
}, []);
return (
<>
<div ref={refCb => {
myRef.current = refCb;
refObserver(refCb);
}}>
Hello world!
</div>
<button onClick={() => {
myRef.current.innerText = `${Math.random()}`;
}}>
Change text!
</button>
</>
)
答案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's render cycle
```lang-jsx
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>
</>
);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论