React Hooks:为什么 useRef Hook 的 .current 为 null? [英] React Hooks: Why is .current null for useRef Hook?

查看:442
本文介绍了React Hooks:为什么 useRef Hook 的 .current 为 null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的组件示例:

function App() {const 观察 = useRef(null);控制台日志(观察到的.当前);返回 (<div ref={observed} className="App"><h1>Hello CodeSandbox</h1><h2>开始编辑,看看神奇的事情发生了!</h2>

);}const rootElement = document.getElementById("root");ReactDOM.render(, rootElement);

我希望 observed.current 是 element 类型,current 不会是空的,而是 div 元素及其所有属性.我的理解是:

  1. 引用被初始化为空值
  2. Null 被引用覆盖

但事实证明,.current 仍然是空的.这很糟糕,因为我想将 Observed 传递给一个需要 Element 类型参数的函数.

https://codesandbox.io/embed/purple-forest-0460k

解决方案

Ref.current 为空,因为直到函数返回并呈现内容后才会设置 ref.useEffect 钩子在每次传递给它的数组内容的值发生变化时触发.通过在数组中传递 observed 并将记录 observed 的回调传递到控制台,可以利用 useEffect 钩子来完成您的任务.

 useEffect(() => {控制台日志(观察到的.当前);}, [观察到的]);

这仅适用于第一次渲染,因为对 ref 的更改不会触发重新渲染.但是关于 useEffect 的一般声明仍然成立.如果要观察 dom 元素的 ref 的更改,可以使用 回调作为参考.

 

{ console.log(el);观察.current = el;}}//或 setState(el)类名="应用程序">

代码沙盒

I have a simple example of a component:

function App() {
  const observed = useRef(null);
  console.log(observed.current);

  return (
    <div ref={observed} className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

I would expect that observed.current would be of type element and current would not be empty but the div element with all its properties. My understanding would be:

  1. The ref is initialised with a value of null
  2. Null is overwritten by the ref

But as it turns out, .current remains empty. This is bad since I want to pass observed to a function that expects an argument of type Element.

https://codesandbox.io/embed/purple-forest-0460k

解决方案

Ref.current is null because the ref is not set till after the function returns and the content is rendered. The useEffect hook fires every time the value of contents of the array passed to it changes. By passing observed in the array and by passing a callback that logs observed to the console, the useEffect hook can be leveraged to accomplish your task.

  useEffect(() => {
    console.log(observed.current);
  }, [observed]);

Edit: This only works on the first render as changes to a ref do not trigger re-renders. But the general statement about useEffect still holds. If you want to observe changes to a ref of a dom element, you can use a callback as ref.

  <div 
    ref={el => { console.log(el); observed.current = el; }} // or setState(el)
    className="App"
  >

Code Sandbox

这篇关于React Hooks:为什么 useRef Hook 的 .current 为 null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆