【问题标题】:How to get exact DOM element using useRef in React如何在 React 中使用 useRef 获取准确的 DOM 元素
【发布时间】:2020-08-18 00:14:19
【问题描述】:

我正在尝试使用 '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 元素以及我缺少什么?

【问题讨论】:

  • 确切的 DOM 元素是什么意思?您正在获取组件。
  • @SILENT 我需要 ListItem 的确切 DOM 元素,之后要添加 `listRef.current && listRef.current.scrollIntoView({behavior: "smooth", block: "nearest"}) ` 滚动到那个。你想让我将滚动代码也添加到代码框链接
  • 检查这可能对你有帮助:stackoverflow.com/questions/54940399/…
  • 您当前的实现是指最后一个元素。您只想滚动到最后一个元素还是列表中的任何元素?
  • @SILENT 是的,这正是问题所在。我不想滚动到最后一个元素,而是想滚动到包含在 searchBar 中输入的第一次出现的 searchText 的元素。

标签: javascript reactjs typescript dom react-hooks


【解决方案1】:

将你的 useRef 更改为

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

【讨论】:

  • 非常感谢,您能否更新我的沙箱,因为我使用的是打字稿,const listRef = React.useRef({}) 在那里出错。谢谢
  • Typescript 类型可能是 { [key: number]: HTMLElement} 。更新并添加了代码框链接
  • @感谢您分享代码框链接,但不幸的是,滚动仍然无法正常工作。有什么遗漏吗?
  • @Lara 哎呀,对不起。忘记了 createRef 部分。更新
【解决方案2】:

代码如下:

声明 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

【讨论】:

  • 非常感谢哈曼,我正在尝试在我的解决方案中实现它,一旦它起作用,我会接受它作为答案。再次感谢
  • 为什么我在const listRef = Array.from({ length: messages.length }, () =&gt; useRef(null));得到React Hook "useRef" cannot be called inside a callback
  • 您还需要更改此设置:&lt;ListItemText ref={listRef[id]} primary={primary} secondary={secondary} /&gt; &lt;/ListItem&gt;。还有 useRef 来自 react 在您已导入 useEffect 的顶部
  • 我这样做了,但没有出现错误,但在这一行 const listRef = Array.from({ length: messages.length }, () =&gt; useRef(null));
猜你喜欢
  • 2020-05-01
  • 1970-01-01
  • 2021-05-15
  • 1970-01-01
  • 2019-07-23
  • 2021-05-29
  • 2021-11-03
  • 1970-01-01
相关资源
最近更新 更多