代码之家  ›  专栏  ›  技术社区  ›  peter flanagan

全部响应引用和查询选择器

  •  1
  • peter flanagan  · 技术社区  · 5 年前

    我用的是反应和 useRef

    以前我用以下方法检查表的行:

    const rows = document.querySelectorAll('table tr');
    

    但是现在我的页面上有多个表,所以我需要使用 ref 以确保我的目标正确 table .

    当我尝试使用REF时,我得到以下错误:

    在“document”:“[对象]上执行“queryselectorall”失败 htmlTableElement]tr'不是有效的选择器。

    我的代码如下:

    const App = () => {
    
       const tableRef = React.useRef(null);
    
       const someMethod = () => {
          // this gives the error specified above
          const rows = document.querySelectorAll(`${testRef.current} tr`);
    
       }
    
       return (
         <>
           <table ref={tableRef}>
              //code here
            </table>
            <button onClick={() => someMethod()}>Random Button</button>
         </>
       )
    }
    

    有人能建议如何正确瞄准 document.querySelectorAll ?

    1 回复  |  直到 5 年前
        1
  •  4
  •   Yury Tarabanko    5 年前

    ref.current 是一个DOM节点(或空)。所以你需要

    const rows = testRef.current.querySelectorAll('tr');
    

    你也可以用 testRef.current.rows 访问行。 MDN