Property 'value' does not exist on type 'never'. when use useRef hook in mui

梦想的初衷 提交于 2021-02-04 18:18:31

问题


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.

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'.

Here is my code snippets:

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

回答1:


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

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>();

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

const accountRef = useRef<HTMLInputElement>();


来源:https://stackoverflow.com/questions/61475289/property-value-does-not-exist-on-type-never-when-use-useref-hook-in-mui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!