摘要
在開發項目中時常有點擊跳轉滾動到錨點的需求,最簡單的錨點定位就是給一個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;