【问题标题】:using ref in typescript nextjs在打字稿 nextjs 中使用 ref
【发布时间】:2021-05-29 18:59:41
【问题描述】:

我在 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>

) }

但我收到了这样的警告

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

有人可以帮我解决吗?

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

【问题讨论】:

    标签: reactjs typescript next.js


    【解决方案1】:

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

    const tmp = useRef<HTMLInputElement>(null)
    

    然后一切都如您所愿。

    Working example on Typescript playground

    【讨论】:

    • 谢谢,我还有 1 个问题,如果我有一个道具示例 props.example(),什么类型的注释?
    • 通常我这样定义 react props:tsplay.dev/m3Akbw 但如果您需要更多帮助,请提出一个新问题,您可以在其中完整解释您的情况并获得所需的适当帮助。
    猜你喜欢
    • 2021-01-02
    • 2021-04-05
    • 2019-10-15
    • 1970-01-01
    • 2021-08-21
    • 2021-01-27
    • 2023-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多