简体   繁体   English

如何在单页分页时重置滚动位置

[英]How to reset scroll position on single page pagination

I try to fix scroll location. 我尝试修复滚动位置。
When clicking on another pagination, scroll location does not be reset. 单击另一个分页时,不会重置滚动位置。

Front : React 前:React
css framework : semantic-ui-react CSS框架:语义UI反应

  Paragraph = () => (
    <p style={{whiteSpace: 'pre-wrap', wordBreak: 'break-all'}}>
      {[this.state.article.content].join('')}
    </p>
  );

  render() {
    return (
      <Container text style={{marginTop: '3em'}}>
        <Header as="h1">{this.state.article.title}</Header>
        <this.Paragraph />
      </Container>
    );
  }
class App extends React.Component {
  render() {
    return (
      <div className="container">
        <FixedMenuLayout />
        <Switch>
          <Route path="/" component={List} />
          <Redirect to="/" />;
        </Switch>
      </div>
    );
  }
}

The full source code is here: 完整的源代码在这里:
https://github.com/jpskgc/article/blob/master/client/src/components/List.tsx https://github.com/jpskgc/article/blob/master/client/src/components/List.tsx

I expect the scroll is reset when clicking another number in pagination component. 我希望在单击分页组件中的另一个数字时重置滚动。
But the actual is not. 但实际并非如此。
Plese take a look below picture. 请看下面的图片。
在此处输入图片说明

After clicking "2" on pagination, I want the scroll is reset like below image. 在分页上单击“ 2”后,我想重置滚动,如下图所示。
在此处输入图片说明

You can add window.scrollTo(0, 0) to your setState callback: 您可以将window.scrollTo(0, 0)添加到setState回调中:

async btnClick(
    event: React.MouseEvent<HTMLAnchorElement>,
    data: PaginationProps
  ) {
    //...

    this.setState({
      articleDatas: this.state.articles.slice(this.state.begin, this.state.end),
    },
    () => window.scrollTo(0, 0));
  }

Also note that your await this.setState won't work as you think. 还要注意,您的await this.setState将无法正常工作。 setState doesn't return a Promise. setState不返回Promise。 If you really want to have async setState , you can make own helper: 如果您确实想要异步setState ,则可以创建自己的帮助器:

setStateAsync(state) {
    return new Promise((resolve) => {
      this.setState(state, resolve)
    });
}

Source . 来源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM