Javascript react ref和查询选择器all
我正在使用react和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 =
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@peterflanaganHTMLTableElement
提供了一个完整的API来操作表行。检查我链接的文章。是的,刚刚检查过