我正在尝试使用'React.useRef(null);'获取List的ListItem中的确切DOM元素。但无法获取,我正在使用以下代码
useEffect(() => {
//This is where i am trying to get the exact DOM element
console.log("listRef", listRef.current);
}, [searchText]);
这是我的密码和框link
如何获取确切的DOM元素以及我缺少什么?
答案 0 :(得分:2)
更改用途参考
const listRef = useMemo(() => messages.map(() => React.createRef<HTMLElement>()), [])
为每个列表项设置
ref={listRef[id]}
调用相应的项目以滚动至使用
listRef && listRef[id] && listRef[id].current.scrollIntoView({behavior: "smooth", block: "nearest"});
https://codesandbox.io/s/material-message-search-0x04c?file=/demo.tsx
答案 1 :(得分:1)
在这里输入代码:
声明refs数组:
const listRef = React.useMemo(() => messages.map(() => React.createRef()), []);
如下更新您的useEffect代码:
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