useRef可以传入任何初始值,不仅仅是null。以下是一个例子:

import { useRef } from "react";

function MyComponent() {
  const inputRef = useRef("");
  const handleClick = () => {
    console.log(inputRef.current.value);
  };
  return (
    <div>
      <input ref={inputRef} type="text" />
      <button onClick={handleClick}>Click me</button>
    </div>
  );
}

在这个例子中,inputRef的初始值是一个空字符串。当用户输入文本时,我们可以通过inputRef.current.value来获取该值。

useRef的调用只能传null吗,能举了个不传null的例子吗

原文地址: http://www.cveoy.top/t/topic/ugN 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录