首页 > 解决方案 > 在打字稿 nextjs 中使用 ref

问题描述

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

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() 的类型注释是什么?

标签: reactjstypescriptnext.js

解决方案


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

const tmp = useRef<HTMLInputElement>(null)

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

Typescript 操场上的工作示例


推荐阅读