我有一个页面,其中每个组件都有滚动功能。但它将来自另一个页面。就像在主页上的路线是"/“我已经设置了滚动
import { Link as Scrolllink, animateScroll as scroll } from 'react-scroll'
<Scrolllink
onClick={() => history.push('/services')}
to="DayCare"
spy={true}
smooth={true}
hashSpy={true}
isDynamic={true}
>
Day care
</Scrolllink>
<Scrolllink
onClick={() => history.push('/services')}
to="Office"
spy={true}
smooth={true}
hashSpy={true}
isDynamic={true}
>
Office
</Scrolllink>与此类似,我已经为所有的目标元素设置了。现在在服务页面中,我已经在该组件之前添加了该目标的id
<div id="DayCare"> <DayCare /></div>
<div id="HomeApartment"> <HomeApartment/></div>
<div id="Office"> <Office/></div>
<div id="MoveInOut"> <MoveInOut/></div>
<div id="Construction"> <Construction/></div>
<div id="Airbnb"> <Airbnb/></div>
<div id="Carpet"> <Carpet/></div>
<div id="Infection"> <Infection/></div>但是我正在推送到"/service“页面,而不是滚动到目标id:如果我点击这个链接,我会转到一个随机的组件,而不是我的目标组件。如何解决此问题。
发布于 2021-08-24 18:46:54
我的应用程序也遇到了同样的问题,我用async函数和react-scroll中的scroll解决了这个问题:
import React from 'react';
import {scroller} from "react-scroll";
import {useHistory} from "react-router-dom";
const Nav = () => {
const history = useHistory();
const scrollTarget = (target) => scroller.scrollTo(target, {smooth: true, duration: 700});
const scrollToPage = async (target) => {
if (history.location.pathname !=='/') {
await history.push('/');
}
scrollTarget(target);
};
return (
<nav>
<div onClick={() => scrollToPage('about')}>About</div>
<div onClick={() => scrollToPage('info')}>Info</div>
<div onClick={() => scrollToPage('contact')}>Contact</div>
</nav>
);
}
export default Nav;发布于 2020-12-01 23:36:24
也许你可以试试react-scrollable-anchor包https://www.npmjs.com/package/react-scrollable-anchor。对我来说,它适用于从另一个页面导航和滚动。
https://stackoverflow.com/questions/65063781
复制相似问题