在打字稿nextjs中使用ref

时间:2021-05-29 18:59:41

标签: reactjs typescript next.js

我在 React 中学习打字稿但收到警告

import {useref} from 'react'

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

) }

但是我收到了这样的警告

Property 'value' does not exist on type 'never'.ts(2339)

有人可以帮我解决吗?

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

1 个答案:

答案 0 :(得分:1)

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

const tmp = useRef<HTMLInputElement>(null)

然后一切都如您所愿。

Working example on Typescript playground