Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript react ref和查询选择器all_Javascript_Reactjs_Ecmascript 6 - Fatal编程技术网

Javascript react ref和查询选择器all

Javascript react ref和查询选择器all,javascript,reactjs,ecmascript-6,Javascript,Reactjs,Ecmascript 6,我正在使用react和useRef 之前,我使用以下方法检查表的行: const rows = document.querySelectorAll('table tr'); const App = () => { const tableRef = React.useRef(null); const someMethod = () => { // this gives the error specified above const rows =

我正在使用react和
useRef

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

const rows = document.querySelectorAll('table 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>
     </>
   )
}
但是现在我的页面上有多个表,所以我需要使用
ref
来确保我的目标是正确的

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

无法对“文档”:“[对象”执行“querySelectorAll” HTMLTableElement]tr'不是有效的选择器

我的代码如下所示:

const rows = document.querySelectorAll('table 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>
     </>
   )
}
const-App=()=>{
const tableRef=React.useRef(null);
const someMethod=()=>{
//这将产生上面指定的错误
const rows=document.querySelectorAll(`${testRef.current}tr`);
}
返回(
//代码在这里
someMethod()}>随机按钮
)
}

任何人都可以建议如何正确定位
文档中的ref。querySelectorAll

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

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

您还可以使用
testRef.current.rows
访问行

您也可以使用react中的
window.document.querySelectorAll
访问您想要的任何组件。

在我可以的时候会给您绿色标志。非常好,从来都不知道我可以访问
行that@peterflanagan
HTMLTableElement
提供了一个完整的API来操作表行。检查我链接的文章。是的,刚刚检查过