简体   繁体   中英

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
css framework : semantic-ui-react

  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

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.
在此处输入图片说明

You can add window.scrollTo(0, 0) to your setState callback:

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. setState doesn't return a Promise. If you really want to have async setState , you can make own helper:

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

Source .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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