在我的案例中执行 React Router 历史推送时如何滚动到页面
How can I scroll to a page when doing React Router history push in my case
我学习了一些 React-router-dom,它有点工作,但因为我有三个 Components
一个接一个,就像一个长页面。然后当我在顶部菜单中单击这样的 about
按钮时;
<Button variant="primary" onClick={() => history.push('/articles')}>
Articles
</Button>
<Button variant="primary" onClick={() => history.push('/stories')}>
Stories
</Button>
<Button variant="primary" onClick={() => history.push('/about')}>
About
</Button>
/about
页面已呈现但未滚动到,因为它是第 3 页。有什么方法可以自动滚动到该页面吗?
我的菜单不是固定的,但每当用户向上滚动菜单时出现,当用户向下滚动时菜单消失,不会阻止内容。
看起来这三个组件组成了一个长页面
React 路由器或 useHistory
中是否内置了一些东西,或者我是否必须想办法让组件知道它们是从主菜单中调用的?然后自己计算如何滚动到可见。
我对 React Redux 知之甚少,我想我可以从菜单按钮调度和操作,然后 mapStateToProp
监听组件中的操作,然后滚动可见。感觉像一个糟糕的黑客不知道。
不确定这是否可行,或者这个 consistent/best 解决方案是否可行,但就目前而言,您可以尝试使用这个
const onAboutPageClick = () =>{
const aboutPageNode = document.getElementById('aboutPage')
aboutPageNode.scrollIntoView({behavior: "smooth"});
history.push('/about')
}
<Button variant="primary" onClick={() => history.push('/articles')}>
Articles
</Button>
<Button variant="primary" onClick={() => history.push('/stories')}>
Stories
</Button>
<Button variant="primary" onClick={onAboutPageClick}>
About
</Button>
..... some other html code
<div id="aboutPage"> Here is about page </div>
在 Dmitriy Sakhno 所说的上述答案中,我认为它给出了一个错误,因为它找不到它,因为页面尚未呈现
所以我使用了 setTimeout 并且它起作用了。
const onAboutPageClick = () => {
history.push('/about')
setTimeout(() => {
const aboutPageNode = document.getElementById('aboutPage');
aboutPageNode.scrollIntoView({behavior: "smooth"});
}, 0);
}
我学习了一些 React-router-dom,它有点工作,但因为我有三个 Components
一个接一个,就像一个长页面。然后当我在顶部菜单中单击这样的 about
按钮时;
<Button variant="primary" onClick={() => history.push('/articles')}>
Articles
</Button>
<Button variant="primary" onClick={() => history.push('/stories')}>
Stories
</Button>
<Button variant="primary" onClick={() => history.push('/about')}>
About
</Button>
/about
页面已呈现但未滚动到,因为它是第 3 页。有什么方法可以自动滚动到该页面吗?
我的菜单不是固定的,但每当用户向上滚动菜单时出现,当用户向下滚动时菜单消失,不会阻止内容。
看起来这三个组件组成了一个长页面
React 路由器或 useHistory
中是否内置了一些东西,或者我是否必须想办法让组件知道它们是从主菜单中调用的?然后自己计算如何滚动到可见。
我对 React Redux 知之甚少,我想我可以从菜单按钮调度和操作,然后 mapStateToProp
监听组件中的操作,然后滚动可见。感觉像一个糟糕的黑客不知道。
不确定这是否可行,或者这个 consistent/best 解决方案是否可行,但就目前而言,您可以尝试使用这个
const onAboutPageClick = () =>{
const aboutPageNode = document.getElementById('aboutPage')
aboutPageNode.scrollIntoView({behavior: "smooth"});
history.push('/about')
}
<Button variant="primary" onClick={() => history.push('/articles')}>
Articles
</Button>
<Button variant="primary" onClick={() => history.push('/stories')}>
Stories
</Button>
<Button variant="primary" onClick={onAboutPageClick}>
About
</Button>
..... some other html code
<div id="aboutPage"> Here is about page </div>
在 Dmitriy Sakhno 所说的上述答案中,我认为它给出了一个错误,因为它找不到它,因为页面尚未呈现 所以我使用了 setTimeout 并且它起作用了。
const onAboutPageClick = () => {
history.push('/about')
setTimeout(() => {
const aboutPageNode = document.getElementById('aboutPage');
aboutPageNode.scrollIntoView({behavior: "smooth"});
}, 0);
}