我正在使用React和useRef
之前,我使用以下代码来检查表格行:
const rows = document.querySelectorAll('table tr');
但是现在我在页面上有多个表格,所以我需要使用ref
来确保我能够定位到正确的table
。
当我尝试使用ref
时,我会遇到以下错误:
在“文档”上执行'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>
</>
)
}
请问如何正确地在document.querySelectorAll
中定位元素的ref
属性?
HTMLTableElement
提供了一个完整的 API 来操作表格行。请查看我链接的文章。 - Yury Tarabanko