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
?
ref.current
是DOM节点(或为null)。所以你需要
const rows = testRef.current.querySelectorAll('tr');
Run Code Online (Sandbox Code Playgroud)
您也可以testRef.current.rows
用来访问行。MDN
归档时间: |
|
查看次数: |
117 次 |
最近记录: |