如何在React中使用useRef获得确切的DOM元素 [英] How to get exact DOM element using useRef in React
本文介绍了如何在React中使用useRef获得确切的DOM元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用'React.useRef(null);'获取列表的ListItem中的确切DOM元素,但无法获取,我正在使用以下代码
I am trying to get the exact DOM element in the ListItem of List using 'React.useRef(null);' but not able to get it, i am using below code
useEffect(() => {
//This is where i am trying to get the exact DOM element
console.log("listRef", listRef.current);
}, [searchText]);
这是我的codesandbox 链接
Here is my codesandbox link
如何获取确切的DOM元素以及我缺少什么?
How to get exact DOM element and what am i missing?
推荐答案
在这里使用代码:
声明refs数组:
const listRef = React.useMemo(() => messages.map(() => React.createRef()), []);
更新您的useEffect代码如下:
Update your useEffect code as below:
useEffect(() => {
//This is where i am trying to get the exact DOM element
let index = 1;
for (let i = 0; i < messages.length; i++) {
if (
messages[i].primary.includes(searchText) ||
messages[i].secondary.includes(searchText)
) {
index = i;
break;
}
}
listRef[index+1].current.scrollIntoView({
behavior: "smooth",
block: "nearest"
});
}, [searchText]);
工作代码示例: https://codesandbox.io/s/material-demo-forked-bm4pl?file=/demo.tsx
这篇关于如何在React中使用useRef获得确切的DOM元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文