【问题标题】:NextJs Link to another page and then scroll using: react-scrollNextJs 链接到另一个页面,然后使用:react-scroll 滚动
【发布时间】:2021-02-22 15:57:42
【问题描述】:

我正在使用 react Next js 链接元素:

import Link from 'next/link';

还有我的应用程序中的一些按钮在点击时滚动到一个元素:

import { Link } from 'react-scroll';

https://www.npmjs.com/package/react-scroll

两者分开工作都很好, 但是我有一个链接可以转到另一页,我想在之后滚动: 链接应该是这样的:

  1. 如果用户位于该链接应该链接到的页面上 - 它应该只滚动到该元素。
  2. 如果用户在任何其他页面,链接应该改变页面,然后滚动到元素。

如何捕捉页面变化并知道是否点击了此链接然后滚动? 或者有什么其他办法解决?

【问题讨论】:

    标签: javascript reactjs scroll react-router next.js


    【解决方案1】:

    我是这样做的:

    index.js

    当 redux 的 state (scrollToElement) 发生变化时,滚动到该元素

    import {useDispatch, useSelector} from "react-redux"
    import {  Element, scroller }from 'react-scroll'
    import {ScrollToElement} from "../src/redux/actions/actions"
    
    const dispatch = useDispatch()
    const {scrollToElement} = useSelector(state=>state.app)
    
    useEffect(()=>{
       if (scrollToElement){
         scroller.scrollTo(scrollToElement, {
           duration: 800,
           delay: 0,
           smooth: 'easeInOutQuart'
         })
         dispatch(ScrollToElement(null))
       }
    
    },[scrollToElement])
    
    return (
    <Element name="YOUR_DIV_NAME" className="element">
    <div>SCROLL HERE</div>
    </Element>
    )
    

    menu.js

    通过链接访问并更改 redux 状态

    import { useDispatch } from "react-redux"
    import Link from "next/link"
    
    const dispatch = useDispatch()
    
    return (
    <Link scroll={false} href="/" >
    <li onClick={()=>dispatch(ScrollToElement("YOUR_DIV_NAME"))}>
    <a>
    Scroll!!
    </a>
    </li >
    </Link>
    )
    

    Action.js

    export const ScrollToElement = (string) =>{
    return  dispatch=>{
        dispatch({type:scrollToElement,payload:string})
    }}
    

    AppReducer.js

    const initialState = {
    scrollToElement:null
    }
    export const appReducer = ( state = initialState,action ) =>{
    switch (action.type){
        case scrollToElement:{
            return {
                ...state,
                scrollToElement: action.payload
            }
        }
       }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-05
      • 1970-01-01
      • 2021-12-17
      • 2020-05-13
      • 1970-01-01
      • 1970-01-01
      • 2018-01-25
      相关资源
      最近更新 更多