简体   繁体   English

使用多个滚动条将滚动反应到 ref

[英]React scroll to ref with multiple scrollbars

I have a small problem that I can't figure out.我有一个小问题,我无法弄清楚。

I have an element inside my page with a scrollbar.我的页面中有一个带有滚动条的元素。 This means I got the main page scrollbar and a second scrollbar.这意味着我得到了主页滚动条和第二个滚动条。 I have a button inside that element that triggers a new div with some content inside of it.我在那个元素中有一个按钮,它触发了一个新的 div,里面有一些内容。 But that div is outside the view of the element so you need to scroll to see it.但是那个 div 在元素的视图之外,所以你需要滚动才能看到它。 This is not really user friendly so I am trying to add a function that when you click on that button it scrolls to the new div.这不是真正的用户友好,所以我试图添加一个 function,当您单击该按钮时,它会滚动到新的 div。

Picture of element: https://imgur.com/8wIOTqo button is the gold coloured one元素图片: https://imgur.com/8wIOTqo按钮是金色的

The problem is that it is using the main page scrollbar and not the scrollbar of the element.问题是它使用的是主页滚动条而不是元素的滚动条。 Does anyone know how to fix this?有谁知道如何解决这一问题? Here is my code这是我的代码

// Function to open the element and scroll to the ref 
function enableOtherAddressActive() {
    secondDeliveryAddressRef.current.scrollIntoView();
    setOtherAddress(true);
  }
<div className="deliveryaddress__different">
   {otherAddress ? (
            <div className="deliveryaddress__different-btn btn btn--primary" onClick={disableOtherAddressActive}>Afwijkend bezorgadres verwijderen</div>
         ) : (
            <div className="deliveryaddress__different-btn btn btn--primary" onClick={enableOtherAddressActive}>Afwijkend bezorgadres toevoegen</div>
              )}
            </div>
            <div className="deliveryaddress__second" ref={secondDeliveryAddressRef}>
              {otherAddress ? (
                <div className="deliveryaddress__inner">
                  <h3 className="deliveryaddress__title">
                    Afwijkend bezorgadres toevoegen
                  </h3>
                </div>
              ) : undefined}
            </div>
          </div>

One of the way to scroll to the element is assigning a id to the div and using scrollInto that滚动到元素的一种方法是为 div 分配一个 id 并使用 scrollInto

I have done in the codesandbox below refer it shows how to scroll into a particular element even if it is nested scrollbar我在下面的代码和框中完成了参考它显示了如何滚动到特定元素,即使它是嵌套滚动条

编辑 stoic-meadow-ny3wb

Code:代码:


  const handleScrollTo = () => {
    setTimeout(() => {
      document.getElementById(`element`) &&
        document.getElementById(`element`).scrollIntoView({
          behavior: "smooth",
          block: "center"
        });
    }, 1000);
  };


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

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