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

转载于:https://www.cnblogs.com/ajanuw/p/10152485.html

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐