reactjs - 在打字稿 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() 的类型注释是什么?
解决方案
您需要提供一个类型,useRef
以便它知道会发生什么。您还需要将其初始化为null
.
const tmp = useRef<HTMLInputElement>(null)
然后一切都按您的预期进行。
推荐阅读
- c++ - 减去 uint16_t 值有点困惑
- c - 如何在不使用循环和默认转换的情况下将联系人号码一一打印?
- javascript - Javascript一次突出显示表中的不同列
- python - 我如何断言一列中的所有值在熊猫中都有特定的长度?
- c# - 操作返回无效状态代码“MethodNotAllowed” - Bot Framework Emulator
- javascript - 使用函数和 IIFE 运行 javascript 代码时的行为差异
- ios - 如何扩展算术运算符以支持可选值 - Swift
- php - Laravel 的别名加载器找不到类
- flutter - 将列中的元素与顶部对齐
- browser - 如何检测来自 chrome 扩展的页面预加载?