How target DOM with react useRef in map

后端 未结 3 1908
一生所求
一生所求 2020-12-04 23:48

I looking for a solution about get an array of DOM elements with react useRef() hook.

example:

const Component = () => 
{

  // In `         


        
3条回答
  •  既然无缘
    2020-12-05 00:30

    I'll expand on skyboyer's answer a bit. For performance optimization (and to avoid potential weird bugs), you might prefer to use useMemo instead of useRef. Because useMemo accepts a callback as an argument instead of a value, React.createRef will only be initialized once, after the first render. Inside the callback you can return an array of createRef values and use the array appropriately.

    Initialization:

      const refs= useMemo(
        () => Array.from({ length: 3 }).map(() => createRef()),
        []
      );
    

    Empty array here (as a second argument) tells React to only initialize refs once. If ref count changes you may need to pass [x.length] as "a deps array" and create refs dynamically: Array.from({ length: x.length }).map(() => createRef()),

    Usage:

      refs[i+1 % 3].current.focus();
    

提交回复
热议问题