“ref”对象是一个通用容器,其current属性是可变的

 

保存dom
function Test() {
const t = useRef(null);

useEffect(() => {
l(t.current); // div
});

return (
<div ref={t}> ... </div>
);
}


保存事件程序
function Test() {
const t = useRef(null);
function handleClick() {
t.current = setTimeout(() => l(1), 2000);
}
function handleClear() {
clearTimeout(t.current);
}

return (
<>
<button onClick={handleClick}>start</button>
<button onClick={handleClear}>clear</button>
</>
);
}


存储以前的值
function Test() {
const t = useRef(null);
const [name, setName] = useState("ajanuw");
useEffect(() => {
t.current = name;
});
const prevName = t.current;
return (
<div>
<input value={name} onChange={e => setName(e.target.value)} />
<h2>{name}</h2>
<p>{prevName}</p>
</div>
);
}

 

相关文章:

  • 2021-07-16
  • 2022-12-23
  • 2021-10-13
  • 2022-12-23
  • 2022-12-23
  • 2021-11-09
  • 2021-10-02
  • 2021-04-09
猜你喜欢
  • 2021-06-28
  • 2021-10-22
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-31
相关资源
相似解决方案