首页 > 解决方案 > 反应滚动到一个没有反应路由器和最基本代码的组件

问题描述

我在一个网页中有多个部分。单击按钮时需要滚动到其中一个组件。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"/>

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

标签: javascriptreactjs

解决方案


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

类似的东西

const elementRef = useRef();


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

阅读更多关于useRef 这里


推荐阅读