useRef for element in loop in react [英] useRef for element in loop in react

查看:34
本文介绍了useRef for element in loop in react的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 React,我有一个以这种方式静态声明的 ref 列表:

Using React, i have a list of ref statically declared this way:

  let line1 = useRef(null);
  let line2 = useRef(null);
  let line3 = useRef(null);
  ...
  //IN MY RENDER PART
  <li ref={(el) => (line1 = el)}>line1</li>
  <li ref={(el) => (line2 = el)}>line1</li>
  <li ref={(el) => (line3 = el)}>line1</li>

然后将 refs 传递给动画函数,一切正常;现在事情发生了一些变化,我使用地图创建了列表项,但我不再能够正确引用该元素;我试过类似的东西:

the refs are then passed to an animation function and everything works correctly; now things changed a bit and i create the list item using map and im no longer able to ref the element correctly; i tried something like:

{menu.menu.map((D) => {
let newRef = createRef();
                    LiRefs.push(newRef);
                    return (
                      <li
                        key={D.id}
                        ref={(el) => (newRef = el)} >
                        {D.label}
                      </li>
                    );
                  })}

但是我传递给动画函数的数组是空的(我猜是因为该函数是在 useEffect 钩子内部调用的,而 LiRefs 还不是 useRef)我也知道我将创建的

  • 的数量,所以我可以在开头声明它们,并使用类似

    but the array i pass to the animation function is empty (i guess because the function is called inside useEffect hook and LiRefs is not yet a useRef) i also know the number of

  • i will create, so i can declare them at the beginning and the reference with something like

    ref={(el) => (`line${i}` = el)}
    

    这不起作用我可以尝试其他任何解决方案吗?

    which is not working any other solution i could try?

    推荐答案

    Issue

    menu 被映射时,这将不起作用,因为它会创建新的 react refs.

    Issue

    This won't work as each render when menu is mapped it creates new react refs.

    使用 ref 保存生成的 ref 数组,并在映射时对其进行赋值.

    Use a ref to hold an array of generated refs, and assign them when mapping.

    const lineRefs = React.useRef([]);
    
    lineRefs.current = menu.menu.map((_, i) => lineRefs.current[i] ?? createRef());
    

    稍后在映射 UI 时,将存储在 lineRefs 中的 react ref 附加到索引 i

    later when mapping UI, attach the react ref stored in lineRefs at index i

    {menu.menu.map((D, i) => {
      return (
        <li
          key={D.id}
          ref={lineRefs.current[i]} // <-- attach stored ref
          {D.label}
        </li>
      );
    })}
    

    这篇关于useRef for element in loop in react的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    相关文章
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆