问题陈述:
单击反应滚动链接时,该链接未突出显示(我使用过spy
)并且它没有滚动到 div 而只是登陆到页面。
还有其他有效的方法吗?正如我正在学习做的反应
页面上下文组件:
export const PageContext = createContext({
pageId: 'homepage',
scrollToPage: () => {}
})
有一个主页组件
const Home = () => {
const [pageId, setPageId] = useState('homepage');
const anotherCompRef = React.useRef();
const profileCompRef = React.useRef();
const scrollToPage = (event) => {
let pageId = event.target ? event.target.getAttribute('data-pageId') : null
if (pageId) {
setPageId(pageId);
Scroll.scroller.scrollTo(pageId, {
duration: 500,
delay: 100,
smooth: true,
spy: true,
exact: true,
offset: -80,
})
}
}
const renderer = () => {
switch (pageId) {
case 'profile':
return <ProfileView profileCompRef={profileCompRef} />
default:
return <AnotherView anotherCompRef={anotherCompRef}/>
}
}
return (
<>
<PageContext.Provider value={{pageId, scrollToPage: e => scrollToPage(e)}}>
<Layout>
{renderer()}
</Layout>
</PageContext.Provider>
</>
)
}
布局组件:
const Layout = ( {children} ) => {
return (
<>
<Header/>
<MainContainer children={children}/>
<Footer />
</>
)
}
export default Layout
配置文件视图组件:
const ProfileView = (props) => {
return (
<>
<ProfileContainer id='profile' ref={props.profileCompRef} >
do stuff
</ProfileContainer>
</>
)
}
export default ProfileView
另一个视图组件
const AnotherView = (props) => {
return (
<>
<AnotherViewContainer id='anotherView' ref={props.anotherCompRef} >
do stuff
</AnotherViewContainer>
</>
)
}
export default AnotherView
标题组件:
const Header = () => {
const pageContext = useContext(PageContext)
return (
<>
<NavbarContainer>
<NavbarMenu>
<NavItem>
<NavLink to='profile' data-pageId='profile' smooth={true} duration={500} spy={true} exact='true' offset={-80} onClick={(e) => pageContext.scrollToPage(e)}>
Profile
</NavLink>
</NavItem>
<NavItem>
<NavLink to='anotherView' data-pageId='anotherView' smooth={true} duration={500} spy={true} exact='true' offset={-80} onClick={(e) => pageContext.scrollToPage(e)}>
Another View
</NavLink>
</NavItem>
</NavbarMenu>
</NavbarContainer>
</>
)
}
export default Header