类型“从不"上不存在属性“值".在 mui 中使用 useRef 钩子时 [英] Property 'value' does not exist on type 'never'. when use useRef hook in mui

查看:21
本文介绍了类型“从不"上不存在属性“值".在 mui 中使用 useRef 钩子时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 material UI 来构建登录和注册页面,使用 useRef 返回一个 TextFiled 引用实例和 xxxRef.current.value 获取输入值.

I am using material UI to build a login and registration page, using useRef to return a TextFiled ref instance, and xxxRef.current.value to get the input value.

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

I can smoothly run my project and can get the value correctly,but the console always reminded me that:

Property 'value' does not exist on type 'never'.

这是我的代码片段:

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 ?? '',
};

推荐答案

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

useRef is generic if you use it with TypeScript, so you can define the referenced element type like const ref = useRef<Type>();

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

Looking into the type definitions for the inputRef property in MaterialUI it states:

/**
 * Pass a ref to the `input` element.
 */
inputRef?: React.Ref<any>;

因此,对于修复,您可以像这样定义参考:

So for a fix you can define your refs like:

const accountRef = useRef<any>();

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

But the ref is passed through the input field inside the component, better type would be:

const accountRef = useRef<HTMLInputElement>();

这篇关于类型“从不"上不存在属性“值".在 mui 中使用 useRef 钩子时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆