【问题标题】:ref object has value for the first time, but ref.current is nullref 对象第一次有值,但 ref.current 为 null
【发布时间】:2021-07-25 09:11:19
【问题描述】:

谁能解释一下这种行为? ref 对象如何第一次具有价值,但 ref.current 是 null ? 实际上第二部分(ref.current = null)是我已经知道的,但第一部分令人惊讶。

export default function App() {
  const [state, setState] = React.useState(0);
  const ref = React.useRef<HTMLButtonElement>(null);
  console.log(ref); // output: {current: HTMLButtonElement}
  console.log(ref.current); // output: null for the first time
                            // output: <button>click</button> after changing the state

  return (
    <div>
      <button onClick={() => setState(state + 1)} ref={ref}>
        click
      </button>
    </div>
  );
}

似乎不知何故,ref,指的是接口之类的东西,但 ref.current 指的是值本身

【问题讨论】:

    标签: reactjs use-ref


    【解决方案1】:
    How is it that ref object has value for the first time
    

    它没有。在命中日志语句时,该对象实际上是{ current: null }。为了证明这一点,将行更改为:

    console.log(JSON.stringify(ref));
    

    对象看起来有值的原因是开发者工具不会评估该对象,直到您在开发工具中单击它,然后它才具有值。

    【讨论】:

      猜你喜欢
      • 2021-09-11
      • 2021-03-09
      • 2014-12-16
      • 2022-12-21
      • 1970-01-01
      • 2021-03-28
      • 2023-03-20
      • 1970-01-01
      • 2023-01-15
      相关资源
      最近更新 更多