gpt4 book ai didi

javascript - react ref 和 queryselectorall

转载 作者:行者123 更新时间:2023-11-30 08:18:39 25 4
gpt4 key购买 nike

我正在使用 React 和 useRef

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

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

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

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

Failed to execute 'querySelectorAll' on 'Document': '[object HTMLTableElement] tr' is not a valid selector.

我的代码如下所示:

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 中的 ref?

最佳答案

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

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

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

关于javascript - react ref 和 queryselectorall,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57556673/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com