【问题标题】:react ref and query selector all全部反应 ref 和查询选择器
【发布时间】:2019-12-24 16:04:00
【问题描述】:

我正在使用 react 和 useRef

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

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

但现在我的页面上有多个表格,所以我需要使用ref 来确保我定位到正确的table

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

在“文档”上执行“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 中的引用?

【问题讨论】:

    标签: javascript reactjs ecmascript-6


    【解决方案1】:

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

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

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

    【讨论】:

    • 我会尽可能给你绿旗。非常好,从来不知道我可以这样访问rows
    • @peterflanagan HTMLTableElement 提供了一个完整的 API 来操作表格行。检查我链接的文章。
    • 是的,刚刚检查过?
    【解决方案2】:

    您还可以在 react 中使用 window.document.querySelectorAll 来访问您希望访问的任何组件。

    【讨论】:

      猜你喜欢
      • 2017-01-08
      • 2020-08-22
      • 2021-11-07
      • 2019-01-22
      • 2012-07-20
      • 2016-09-16
      • 1970-01-01
      • 2012-11-03
      • 1970-01-01
      相关资源
      最近更新 更多