How to use refs in React with Typescript

前端 未结 15 1460
闹比i
闹比i 2020-11-28 05:03

I\'m using Typescript with React. I\'m having trouble understanding how to use refs so as to get static typing and intellisense with respect to the react nodes referenced by

15条回答
  •  隐瞒了意图╮
    2020-11-28 05:26

    For those looking on how to do it when you have an array of elements:

    const textInputRefs = useRef<(HTMLDivElement | null)[]>([])
    
    ...
    
    const onClickFocus = (event: React.BaseSyntheticEvent, index: number) => {
        textInputRefs.current[index]?.focus()
    };
    
    ...
    
    {items.map((item, index) => (
         textInputs.current[index] = ref}
        />
        

提交回复
热议问题