【问题标题】:Property 'value' does not exist on type 'never'. when use useRef hook in mui“从不”类型上不存在属性“值”。在 mui 中使用 useRef 挂钩时
【发布时间】:2020-08-11 23:26:22
【问题描述】:

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

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

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

这是我的代码sn-ps:

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

【问题讨论】:

    标签: reactjs typescript ecmascript-6 material-ui react-hooks


    【解决方案1】:

    useRef 在 TypeScript 中使用时是通用的,因此您可以定义引用的元素类型,如 const ref = useRef&lt;Type&gt;();

    查看 MaterialUI 中 inputRef 属性的类型定义:

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

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

    const accountRef = useRef<any>();
    

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

    const accountRef = useRef<HTMLInputElement>();
    

    【讨论】:

    • 学到了一些东西 :) 类似于 useState&lt;any&gt; 谢谢!
    【解决方案2】:

    使用 useRef() 时,正确的答案应该是使用正确的 Type (HTMLInputElement):

      const inputRef = useRef<HTMLInputElement>();
      const [caretPosition, setCaretPosition] = useState<number | null>(null);
    
      const updateCaretPosition = () => {
        inputRef.current && setCaretPosition(inputRef.current.selectionStart);
      };
    

    【讨论】:

      【解决方案3】:

      请注意,还有其他类型可以添加到 useRef。

      可能还有其他类型:

      • HTMLElement
      • HTMLFormElement
      • number
      • string
      • 等等……

      useRef 通常用于使用 HTML 元素的引用,但它也可以用于存储数据。

      【讨论】:

        猜你喜欢
        • 2022-01-02
        • 1970-01-01
        • 2021-04-03
        • 2021-02-06
        • 2017-10-24
        • 2020-01-29
        • 2019-05-05
        • 2017-06-23
        相关资源
        最近更新 更多