Javascript Typescript对象可能是';空';在react中使用ref聚焦
typescript仍然给我错误信息 对象可能为“null”。ts(2531) 即使我这样做Javascript Typescript对象可能是';空';在react中使用ref聚焦,javascript,reactjs,typescript,ecmascript-6,Javascript,Reactjs,Typescript,Ecmascript 6,typescript仍然给我错误信息 对象可能为“null”。ts(2531) 即使我这样做 myRef && myRef.current && myRef.current.focus(); 如果我使用 myRef?.current?.focus(); 我得到 Property 'focus' does not exist on type 'never'.ts(2339) 可选链接是处理此类语句的更好方法。这不会给您带来任何错误:- myRef?.curre
myRef && myRef.current && myRef.current.focus();
如果我使用
myRef?.current?.focus();
我得到
Property 'focus' does not exist on type 'never'.ts(2339)
可选链接是处理此类语句的更好方法。这不会给您带来任何错误:-
myRef?.current?.focus()
定义引用时,应指定引用的类型:
const myRef=useRef(null);
(请注意,上面假设您像
一样使用它-如果手动设置myRef.current
,则需要将类型指定为
完成此操作后,您应该能够使用以下各项:
myRef.current?.focus()
请注意,您不需要在
myRef
上使用存在性检查-这将始终是一个具有当前属性的对象-这就是react的API的工作方式。使typescript保持静默并告诉typescript您知道自己在做什么。
您可以在变量前面使用感叹号(!)
,您知道它可以是null
。
与现有场景类似,如果在某些场景中“当前”可以为空,并且您希望为空
typescript上不显示错误
myRef.!current.focus()
myRef
的类型是什么?(您是如何声明的?)发布myRef
的类型我讨厌typescript