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

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

其他回答

以上所有的方法对我都不起作用——不知道为什么,但是:

componentDidMount(){
    document.getElementById('HEADER').scrollIntoView();
}

working,其中HEADER是HEADER元素的id

对于那些使用钩子的人,下面的代码可以工作。

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

注意,你也可以直接导入useEffect:

我正在使用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>
)

钩的解决方案:

创建一个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

我正在使用React Hooks,想要一些可重用的东西,但也想要一些我可以随时调用的东西(而不是仅仅在渲染之后)。

// utils.js
export const useScrollToTop = (initialScrollState = false) => {
  const [scrollToTop, setScrollToTop] = useState(initialScrollState);

  useEffect(() => {
    if (scrollToTop) {
      setScrollToTop(false);
      try {
        window.scroll({
          top: 0,
          left: 0,
          behavior: 'smooth',
        });
      } catch (error) {
        window.scrollTo(0, 0);
      }
    }
  }, [scrollToTop, setScrollToTop]);

  return setScrollToTop;
};

然后使用钩子你可以做:

import { useScrollToTop } from 'utils';

const MyPage = (props) => {
  // initialise useScrollToTop with true in order to scroll on page load 
  const setScrollToTop = useScrollToTop(true);

  ...

  return <div onClick={() => setScrollToTop(true)}>click me to scroll to top</div>
}