简体   繁体   中英

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'.

  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:

const inputRef = React.useRef();
  const updateSelectionStart = () =>
    setSelectionStart(inputRef.current?.selectionStart);

I fixed it by doing this:

const updateSelectionStart = () => {
    setCursorPosition(inputRef.current!.selectionStart || 0);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM