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

pet*_*gan 1 javascript ecmascript-6 reactjs

我正在使用react和 useRef

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

const rows = document.querySelectorAll('table tr');
Run Code Online (Sandbox Code Playgroud)

但是现在我的页面上有多个表,因此我需要使用a ref来确保定位正确table

当我尝试使用ref时,出现以下错误:

无法对'Document'执行'querySelectorAll':'[object 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>
     </>
   )
}
Run Code Online (Sandbox Code Playgroud)

谁能建议如何正确定位ref中的参考document.querySelectorAll

Yur*_*nko 5

ref.current是DOM节点(或为null)。所以你需要

const rows = testRef.current.querySelectorAll('tr');
Run Code Online (Sandbox Code Playgroud)

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