类型“从不”上不存在属性“值”。在 mui 中使用 useRef 钩子时

Yeo*_*_Li 8 typescript ecmascript-6 reactjs material-ui react-hooks

我正在使用Material UI来构建登录和注册页面,useRef用于返回TextFiled ref 实例,并xxxRef.current.value获取输入值。

我可以顺利运行我的项目并且可以value正确获取?但是控制台总是提醒我:

Property 'value' does not exist on type 'never'.
Run Code Online (Sandbox Code Playgroud)

这是我的代码片段?

const accountRef = useRef();

<TextField
            variant="outlined"
            margin="normal"
            required
            fullWidth
            id="account"
            label="Account"
            name="account"
            autoComplete="account"
            autoFocus
            defaultValue={account}
            inputRef={accountRef}
/>


const payload = {
      account: accountRef.current?.value ?? '',
      password: passwordRef.current?.value ?? '',
      nickname: nicknameRef.current?.value ?? '',
};
Run Code Online (Sandbox Code Playgroud)

Mar*_*tin 13

useRef 如果您将它与 TypeScript 一起使用,则它是通用的,因此您可以定义引用的元素类型,例如 const ref = useRef<Type>();

查看inputRefMaterialUI 中属性的类型定义,它指出:

/**
 * Pass a ref to the `input` element.
 */
inputRef?: React.Ref<any>;
Run Code Online (Sandbox Code Playgroud)

因此,对于修复,您可以定义您的 refs,如:

const accountRef = useRef<any>();
Run Code Online (Sandbox Code Playgroud)

但是 ref 是通过组件内的输入字段传递的,更好的类型是:

const accountRef = useRef<HTMLInputElement>();
Run Code Online (Sandbox Code Playgroud)

  • 学到了一些类似于 `useState&lt;any&gt;` 的东西,谢谢! (2认同)

小智 5

正确的答案应该是在使用 useRef() 时使用正确的类型 (HTMLInputElement):

  const inputRef = useRef<HTMLInputElement>();
  const [caretPosition, setCaretPosition] = useState<number | null>(null);

  const updateCaretPosition = () => {
    inputRef.current && setCaretPosition(inputRef.current.selectionStart);
  };
Run Code Online (Sandbox Code Playgroud)


eas*_*ipt 5

就像 Martin 所说,使用 HTMLInputElement 类型并在 useRef 中添加 null。输入元素内的 ref 属性错误已消失。

const input = useRef<HTMLInputElement>(null)
Run Code Online (Sandbox Code Playgroud)