[英]Errors using useRef with Typescript
I am trying to use useRef as shown below with typescript strict set to On, but I keep getting 'Object is possibly 'undefined'.我正在尝试使用 useRef ,如下所示,typescript strict 设置为 On,但我不断收到“对象可能是“未定义”的消息。
const inputRef = React.useRef();
const updateSelectionStart = () =>
setSelectionStart(inputRef.current.selectionStart);
I also tried with this:我也试过这个:
const inputRef = useRef<HTMLInputElement>(null);
and
const inputRef = useRef<HTMLInputElement | null>(null);
And nothing.没事了。
Any suggestions about how to do it without typescript errors?关于如何在没有打字稿错误的情况下做到这一点的任何建议?
Try using typescript optional chaining feature as below:尝试使用 typescript 可选链接功能,如下所示:
const inputRef = React.useRef();
const updateSelectionStart = () =>
setSelectionStart(inputRef.current?.selectionStart);
I fixed it by doing this:我通过这样做修复了它:
const updateSelectionStart = () => {
setCursorPosition(inputRef.current!.selectionStart || 0);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.