在打字稿 nextjs 中使用 ref

jus*_*est 2 typescript reactjs next.js

我在 React 中学习 TypeScript 但收到警告

import {useref} from 'react'

export default function test(){
   cons tmp = useRef()
   const data = tmp.current?.value
   return (
      <div>
        <input type ="text" ref={tmp}/>
      </div>

) }
Run Code Online (Sandbox Code Playgroud)

但我收到这样的警告

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

有人可以帮我解决它吗?

还有一个问题, props.example() 的类型注释是什么?

Ale*_*yne 5

您需要提供一个类型,useRef以便它知道会发生什么。您还需要将其初始化为null.

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

然后一切都会按您的预期进行。

Typescript 游乐场上的工作示例