【问题标题】:Typescript Object is possibly 'null' focusing using ref in reactTypescript Object 可能是“null”焦点,在 react 中使用 ref
【发布时间】:2020-09-19 12:09:31
【问题描述】:
打字稿仍然给我错误
对象可能是'null'.ts(2531)
即使我这样做
myRef && myRef.current && myRef.current.focus();
如果我使用
myRef?.current?.focus();
我明白了
Property 'focus' does not exist on type 'never'.ts(2339)
【问题讨论】:
标签:
javascript
reactjs
typescript
ecmascript-6
【解决方案1】:
当你定义你的引用时,你应该指定它将是什么类型:
const myRef = useRef<HTMLElement>(null);
(请注意,以上假设您像 <div ref={myRef}> 一样使用它 - 如果您手动设置 myRef.current,则需要将类型指定为 <HTMLElement|null>。
完成此操作后,您应该能够使用以下内容:
myRef.current?.focus()
请注意,您不需要对 myRef 使用存在性检查 - 这将始终是具有 current 属性的对象 - 这就是 react 的 API 的工作原理。
【解决方案2】:
让打字稿保持沉默并告诉打字稿您知道自己在做什么。
你可以在你知道它可以是null的变量之前使用exclamation mark(!)。
就像在现有场景中一样,如果 "current" 在某些场景中可以为空并且您想要
打字稿不显示错误。
myRef.!current.focus()