【发布时间】: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 指的是值本身
【问题讨论】: