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

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

问题描述

我正在使用材料UI 通过 useRef 返回 TextFiled 引用实例和 xxxRef.current.值以获取输入值.

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

如果与TypeScript一起使用,

推荐答案

useRef 是通用的,因此可以定义引用的元素类型,例如 const ref = useRef< Type>();

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天全站免登陆