我有个问题,我不知道怎么解决。 在我的react组件中,我在底部显示了一个很长的数据列表和一些链接。 点击任何链接后,我在列表中填充了新的链接集合,需要滚动到顶部。

问题是-如何滚动到顶部后,新的集合呈现?

'use strict';

// url of this component is #/:checklistId/:sectionId

var React = require('react'),
  Router = require('react-router'),
  sectionStore = require('./../stores/checklist-section-store');


function updateStateFromProps() {
  var self = this;
  sectionStore.getChecklistSectionContent({
    checklistId: this.getParams().checklistId,
    sectionId: this.getParams().sectionId
  }).then(function (section) {
    self.setState({
      section,
      componentReady: true
    });
  });

    this.setState({componentReady: false});
 }

var Checklist = React.createClass({
  mixins: [Router.State],

  componentWillMount: function () {
    updateStateFromProps.call(this);
  },

  componentWillReceiveProps(){
    updateStateFromProps.call(this);
   },

render: function () {
  if (this.state.componentReady) {
    return(
      <section className='checklist-section'>
        <header className='section-header'>{ this.state.section.name }   </header>
        <Steps steps={ this.state.section.steps }/>
        <a href=`#/${this.getParams().checklistId}/${this.state.section.nextSection.Id}`>
          Next Section
        </a>
      </section>
    );
    } else {...}
  }
});

module.exports = Checklist;

当前回答

在反应路由有一个问题,如果我们重定向到新的路由,那么它不会自动带你到页面的顶部。

就连我也有同样的问题。

我只是将单行添加到组件中,它就像黄油一样工作。

componentDidMount() {
    window.scrollTo(0, 0);
}

参考:反应训练

其他回答

没有什么对我有用,除了:

componentDidMount(){

    $( document ).ready(function() {
        window.scrollTo(0,0);
    });
}

这个解决方案既适用于功能组件,也适用于类基。

首先,我不喜欢每次重新渲染时滚动到顶部的想法,相反,我喜欢附加函数到特定的事件。

步骤#1:创建一个ScrollToTop函数

const scrollToTop = () => {
    window.scrollTo({
        top: 0,
        behavior: "smooth",
    });
};

步骤2:在事件(如onClick)上调用此函数

onRowClick={scrollToTop()}
// onClick={scrollToTop()}
// etc...

所有的解决方案都谈论在componentDidMount或componentDidUpdate上添加滚动,但使用DOM。

我做了所有这些,但都没用。

所以我找到了另一种适合我的方法。

添加 componentDidUpdate(){窗口。scrollTo(0,0)} 在header中,我的是<Switch></Switch>元素。只要在应用里免费就行了。

我还发现了一些关于ScrollRestoration的东西,但我现在很懒。现在就用“DidUpdate”的方式吧。

在功能组件中使用hook, 假设在结果道具中有更新时组件更新

import React, { useEffect } from 'react';

export const scrollTop = ({result}) => {
  useEffect(() => {
    window.scrollTo(0, 0);
  }, [result])
}

钩的解决方案:

创建一个ScrollToTop钩子


    import { useEffect } from "react";
    import { withRouter } from "react-router-dom";

    const ScrollToTop = ({ children, location: { pathname } }) => {
      useEffect(() => {
        window.scrollTo({
          top: 0,
          left: 0,
          behavior: "smooth"
        });
      }, [pathname]);

      return children || null;
    };

    export default withRouter(ScrollToTop);

用它包装你的应用程序


    <Router>
        <ScrollToTop>
           <App />
        </ScrollToTop>
    </Router>

文档:https://reacttraining.com/react-router/web/guides/scroll-restoration