“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>
);
}
所有评论(0)