react useRef()函数

“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>
);
}

 

posted on 2020-11-06 17:54  ranyonsue  阅读(2094)  评论(0编辑  收藏  举报

导航