我正在使用 React Next js 链接元素:
import Link from 'next/link';
还有我的应用程序中的一些按钮,它们在单击时滚动到一个元素:
import { Link } from 'react-scroll';
https://www.npmjs.com/package/react-scroll
两者分开工作都很好, 但是我有一个转到另一页的链接,我想在之后滚动: 该链接应该像这样工作:
- 如果用户在该链接应该链接到的页面上 - 它应该只滚动到该元素。
- 如果用户在任何其他页面上,链接应该改变页面然后滚动到该元素。
我如何捕捉页面变化并知道是否单击了此链接然后滚动? 或者有什么办法可以解决?
最佳答案
我是这样做的:
索引.js
When state (scrollToElement) at redux is changing , then scroll to the element
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>
)
菜单.js
Go by Link and change redux state
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
}
}
}
关于javascript - NextJs 链接到另一个页面,然后使用 : react-scroll 滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64773540/