【问题标题】:useRef react hook to extract list elementsuseRef 反应钩子提取列表元素
【发布时间】:2021-04-23 08:38:43
【问题描述】:

您好,我将 document.querySelectorAll 重写为 useRef 以提取列表元素和

我想使用 ref 获取[li,li,li]

return (
    <div id="container">
      <ul ref={ref1}>
        <li>About</li>
        <li>Contact</li>
        <li>Pricing</li>
        <div ref={ref2} />
        <div ref={ref3} />
      </ul>
    </div>
  );

使用const liEls = [...document.querySelectorAll("ul li")];

返回 [li, li, li](这是我想用 useRef 得到的)

但是当我用 useRef ref={ref1} 重写时 和

 const ref1 = useRef(null);
 useEffect(() => {
    if (ref1.current === null) return;
    else {
      console.log("ref1.current", ref1.current);
    }
  }, [ref1.current]);

我充满了&lt;ul&gt;...&lt;/ul&gt; 部分而不是列表数组[li,li,li]

有没有办法提取列表数组?

【问题讨论】:

  • 改用ref1.current.children。 (或ref.current.querySelectorAll('li')
  • 我没有看到任何实际尝试使用ref1.current 的孩子的东西。另请注意,元素也有 querySelectorAll,因此您可以在 ref1.current 上使用它来复制您通过基于文档的 qSA 获得的内容。
  • 语义上,将div 元素作为ul 的直接子元素是无效的,因此“检查它是否是li”首先应该不是问题。老实说,您应该重构您的 HTML 以将 div 从 ul 中取出,这样您就不必检查是否是 li

标签: javascript html reactjs use-ref


【解决方案1】:

您的 ref 位于 &lt;ul&gt; 元素上,这就是它返回 &lt;ul&gt; 的原因。如果要在其中创建子元素列表,可以执行以下操作:

useEffect(() => {
    if (ref1.current) {
      const list = Object.entries(ref1.current.children).map(([index, child]) => {
        return child
      })
      // do something with list
    }
  }, [ref1]);

另外,你不应该将 type 作为

的子元素

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-01
    • 2018-01-24
    • 2021-03-28
    • 1970-01-01
    • 2022-10-14
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    相关资源
    最近更新 更多