【问题标题】:react scroll to a component without react router and with most basic code反应滚动到没有反应路由器和最基本代码的组件
【发布时间】:2021-08-08 09:57:36
【问题描述】:

我在一个网页中有多个部分。单击按钮时需要滚动到其中一个组件。 ref 的路由器是多余的或者不是必需的,因为它只需要滚动到页面的一部分。

试过这个:

// on return function
<Button onClick={() =>
                    document
                      .getElementsByClassName("scrollhere")
                      .scrollIntoView() //error not a function.
                  }
                >
                Go to Download Section
</Button>

<Section1/> // Section is equivalent of div 
<Section2/>
<Section3 className="scrollhere"/>
<Section4 id="downloadSection"/>

如何用最基本的代码滚动到某个点?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    利用useRef 挂钩来引用一个元素,然后滚动到它。

    类似的东西

    const elementRef = useRef();
    
    
    //Later in the code
    <button onClick={() => elementRef.current.scrollIntoView()}/>
    <div className="scrollhere" ref={elementRef}/>
    
    

    阅读更多关于useRefhere

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-27
      • 2020-09-26
      • 2019-11-18
      • 2020-07-29
      • 2020-09-30
      • 2021-06-27
      • 1970-01-01
      • 2016-02-24
      相关资源
      最近更新 更多