【发布时间】:2021-06-03 03:27:10
【问题描述】:
我有以下代码:
const queryInput = useRef()
const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
e.preventDefault()
if (queryInput && queryInput.current) {
console.log(`queryInput.current.value`, queryInput?.current?.value ?? null)
}
}
return (
...
我在 vscode 中收到以下错误:
(property) MutableRefObject<undefined>.current: undefined
Object is possibly 'undefined'.ts(2532)
尽管我试图用 if 子句和可选的链接运算符来避免它。
从控制台我得到同样的错误:
$ npx tsc
pages/_app.tsx:14:47 - error TS2532: Object is possibly 'undefined'.
14 console.log(`queryInput.current.value`, queryInput?.current?.value ?? null)
~~~~~~~~~~~~~~~~~~~
Found 1 error.
还检查了这个 SO 答案:How can I solve the error 'TS2532: Object is possibly 'undefined'?
还有这篇博文:https://linguinecode.com/post/how-to-solve-typescript-possibly-undefined-value
但我似乎无法解决问题
顺便说一句,这是我的 ts 版本:
"devDependencies": {
"@types/node": "^14.14.31",
"@types/react": "^17.0.2",
"typescript": "^4.2.2"
【问题讨论】:
-
尝试将
null传递给您的useRef钩子 -useRef(null);看看是否有帮助。 -
是的!请将其添加为 aswer,以便我接受它
标签: reactjs typescript