简体   繁体   English

如何滚动到React中动态添加的元素

[英]How to scroll to a dynamically added element in react

I have this code that I call in button click to scroll to the bottom of a page: 我在按钮单击中调用以下代码以滚动到页面底部:

const el = useRef<HTMLDivElement>(null);

const ScrollToBottom = () => {
    if (el.current !== null)
        el!.current!.scrollIntoView({ block: 'end', behavior: 'smooth' });
}

This helps me scroll to the element that has the el reference, for example: 这有助于我滚动到具有el引用的元素,例如:

<div id={'el'} ref={el}></div>

But, I want to scroll to the last element added or updated, which is not necessarily always at the end of the page. 但是,我想滚动到最后添加或更新的元素,它不一定总是在页面的末尾。 With the approach I am using now, I do not think it is possible. 用我现在使用的方法,我认为不可能。 This is because I would need to remove all possible ref={el} attributes from other dom elements, and add it to the dynamic component recently added. 这是因为我需要从其他dom元素中删除所有可能的ref={el}属性,并将其添加到最近添加的动态组件中。 I do not know if this is possible. 我不知道这是否可能。

I wonder if there is a way to achieve this? 我想知道是否有办法实现这一目标?

This may not be exactly what you want, but you could move the scrollIntoView logic into the child component and run it on mount (via componentDidMount or useEffect). 这可能不完全是您想要的,但是您可以将scrollIntoView逻辑移到子组件中并在安装时运行(通过componentDidMount或useEffect)。 It would look something like this: https://codesandbox.io/s/sad-villani-jhmuw 它看起来像这样: https : //codesandbox.io/s/sad-villani-jhmuw

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM