我有个问题,我不知道怎么解决。 在我的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;

当前回答

以上答案目前对我来说都没用。事实证明,. scrollto并不像. scrollintoview那样广泛兼容。

在App.js中,我们在componentWillMount()中添加了

this.props.history.listen((location, action) => {
        setTimeout(() => { document.getElementById('root').scrollIntoView({ behavior: "smooth" }) }, 777)
    })

这是唯一适用于我们的解决方案。root是我们应用的ID。“平滑”行为并不适用于每个浏览器/设备。777的超时有点保守,但我们在每个页面上都加载了大量数据,所以通过测试,这是必要的。更短的237可能适用于大多数应用程序。

其他回答

如果我假设您正在呈现一个章节,比如每页一本书,那么您所需要做的就是将此添加到代码中。这对我来说就像魔法一样有效。

    componentDidUpdate(prevProps) {
      if (prevProps.currentChapter !== this.props.currentChapter) {
        window.scrollTo(0, 0);
      }
    }

这样,你就不需要在被呈现的组件上创建一个引用。

我正在使用react-router ScrollToTop组件,该组件的代码在react-router文档中描述

https://reacttraining.com/react-router/web/guides/scroll-restoration/scroll-to-top

我在单个路由文件中更改代码,之后不需要在每个组件中更改代码。

示例代码-

步骤1 -创建ScrollToTop.js组件

import React, { Component } from 'react';
import { withRouter } from 'react-router';

class ScrollToTop extends Component {
  componentDidUpdate(prevProps) {
    if (this.props.location !== prevProps.location) {
      window.scrollTo(0, 0)
    }
  }

  render() {
    return this.props.children
  }
}

export default withRouter(ScrollToTop)

步骤2 -在App.js文件中,在<Router后添加ScrollToTop Component

const App = () => (
  <Router>
    <ScrollToTop>
      <App/>
    </ScrollToTop>
  </Router>
)

我有一段时间也有同样的问题。添加窗口。scrollTo(0,0);到每个页面都是痛苦和冗余的。所以我添加了一个HOC,它将包装我所有的路由,它将留在BrowserRouter组件:

 <ScrollTop>
    <Routes />
  </ScrollTop>

在ScrollTopComponent内部,我们有以下内容:

import React, { useEffect } from "react";
import { useLocation } from "react-router-dom";

const ScrollTop = (props) => {
  const { children } = props;

  const location = useLocation();

  useEffect(() => {
    window.scrollTo(0, 0);
  }, [location]);

  return <main>{children}</main>;
};

export default ScrollTop;

我在index.html页面上添加了一个事件侦听器,因为所有页面加载和重新加载都是通过它完成的。下面是代码片段。

// Event listener
addEventListener("load", function () {
    setTimeout(hideURLbar, 0);
}, false);
  
function hideURLbar() {
    window.scrollTo(0, 1);
}

平滑滚动到顶部。在钩子中,你可以在生命周期安装状态中使用此方法进行一次渲染

useEffect(() => {
  window.scrollTo({top: 0, left: 0, behavior: 'smooth' });
}, [])