javascript - 反应滚动到一个没有反应路由器和最基本代码的组件
问题描述
我在一个网页中有多个部分。单击按钮时需要滚动到其中一个组件。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"/>
如何使用最基本的代码在某个点滚动?
解决方案
利用useRef
钩子来引用一个元素,然后滚动到它。
类似的东西
const elementRef = useRef();
//Later in the code
<button onClick={() => elementRef.current.scrollIntoView()}/>
<div className="scrollhere" ref={elementRef}/>
阅读更多关于useRef
这里
推荐阅读
- c++ - 仅在 C++ 中使用递归删除元音和特殊字符,同时对辅音进行修饰
- android - Android JAVA中MVP模式中的Firestore数据提取序列
- javascript - 如何将 React 组件呈现的按钮绑定到该组件中的函数?
- database-design - 您如何识别维度表中的条目来自哪个来源?- 数据仓库
- r - 如何估计带岛屿的空间 SAR 模型?
- cypress - 赛普拉斯和 Applitools:[眼睛测试未开始]:错误:请求失败,状态码 400(错误请求)
- .net-core - 如何识别没有原始信封ID的电子邮件
- kubernetes - 跨多个节点的服务节点端口
- maven - Kotlin - 用“@OptionalExpectation”注释的声明只能在通用模块源中使用
- php - 正确调用 img src 中的 server_name