zoukankan      html  css  js  c++  java
  • Ref实现导航滚动定位

    摘要

      在开发项目中时常有点击跳转滚动到锚点的需求,最简单的锚点定位就是给一个a标签,a标签的href = ‘#锚点’,然后给需要跳转的锚点一个id = ‘锚点’。参考最简单的锚点跳转实现方式,在React中使用useRef来实现跳转锚点的功能。

    功能具体步骤

    1、创建空的Ref  

    import React, { useRef } from 'react';
    
    const Layout = () => {
        const pageTopRef = useRef(null);
        const sectionEventInfoRef = useRef(null);
    
      return (
          <div>滚动内容</div>
      )  
    }

    2、跳转锚点函数

      Element.scrollIntoView() 方法让当前的元素滚动到浏览器窗口的可视区域内。我们可以利用该方法搭配Ref实现跳转锚点的功能,behavior属性可以定义动画过渡效果,跳转锚点时滚动效果平滑些。具体代码代码如下:

      // 点击导航按钮,滚动到页面中相对应的区域
      const handleClickNavItem = ref => {
        setIsWork(false);
        if (ref.current) {
          ref.current.scrollIntoView({ behavior: "smooth" });
        }
      }

    3、锚点

       bind()绑定ref,锚点处在绑定对应跳转ref,简化式代码如下所示:

    import React, { useRef } from 'react';
    import '../style.scss';
    
    const Layout = () => {
      const pageTopRef = useRef(null);
      const sectionEventInfoRef = useRef(null);
    
      // 点击导航按钮,滚动到页面中相对应的区域
      const handleClickNavItem = ref => {
        if (ref.current) {
          ref.current.scrollIntoView({ behavior: "smooth" });
        }
      }
    
      return (
        <div className="activity-area">
          <div className="actAr-wrapper">
            <div className="actAr-tabs">
              <button onClick={handleClickNavItem.bind(null, pageTopRef)}>首页</button>
              <button onClick={handleClickNavItem.bind(null, sectionEventInfoRef)}>活动详情</button>
              <button onClick={openEWorks}>精选作品</button>
            </div>
            <div className="actAr-content">
              <!-- 锚点一 -->
              <div ref={pageTopRef}>
                回到首页的锚点
              </div>
              <!-- 锚点二 -->
              <div ref={sectionEventInfoRef}>
                活动详情的锚点
              </div>
            </div>
          </>
        </div>
      )
    }
    
    export default Layout;
    
  • 相关阅读:
    js 类型转换学习
    Prototypes in Javascript 收集.__proto__
    不想说作用域scope,因为是scopeTree,
    在家学习 利器 记录每日点滴
    图片切换特效的分析和学习
    js 无缝滚动效果学习
    MySQL 在高并发下的 订单撮合 系统使用 共享锁 与 排他锁 保证数据一致性
    (二)区块链的共识算法:PoS 及其 例子 代码 实现
    以太坊: ETH 发送交易 sendRawTransaction 方法数据的签名 和 验证过程
    Golang 的 协程调度机制 与 GOMAXPROCS 性能调优
  • 原文地址:https://www.cnblogs.com/BlueBerryCode/p/12931332.html
Copyright © 2011-2022 走看看