我是这样做的:
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
}
}
}