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

其他回答

你可以在路由器上这样做:

ReactDOM.render((
<Router onUpdate={() => window.scrollTo(0, 0)} history={browserHistory}>
     <Route path='/' component={App}>
        <IndexRoute component={Home}></IndexRoute>
        <Route path="/about" component={About}/>
        <Route path="/work">
            <IndexRoute component={Work}></IndexRoute>
            <Route path=":id" component={ProjectFull}></Route>
        </Route>
        <Route path="/blog" component={Blog}/>
    </Route>
 </Router>
), document.getElementById('root'));

onUpdate={() =>窗口。scrollTo(0,0)}将滚动顶部。 更多信息请查看:codepen link

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

就连我也有同样的问题。

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

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

参考:反应训练

我已经尝试过@sledgeweight解决方案,但它并不适用于某些视图。但是添加setTimeout似乎可以完美地工作。以防有人遇到和我一样的问题。下面是我的代码。

import { useEffect } from 'react'
import { useLocation } from 'react-router-dom'

const ScrollToTop = () => {
    const { pathname } = useLocation()
    useEffect(() => {
        console.log(pathname)
        /* settimeout make sure this run after components have rendered. This will help fixing bug for some views where scroll to top not working perfectly */
        setTimeout(() => {
            window.scrollTo({ top: 0, behavior: 'smooth' })
        }, 0)
    }, [pathname])
    return null
}

export default ScrollToTop

在AppRouter.js中使用它

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

如果所有人都想做一些简单的事情,这里有一个解决方案,对每个人都适用

添加这个迷你函数

scrollTop()
{
    window.scrollTo({
        top: 0,
        behavior: "smooth"
    });
}

从页脚调用函数,如下所示

<a className="scroll-to-top rounded" style={{display: "inline"}} onClick={this.scrollTop}>TOP</a>

如果你想添加漂亮的样式,这里是CSS

.scroll-to-top { 位置:固定; 右:1快速眼动; 底部:1快速眼动; 显示:没有; 宽度:2.75快速眼动; 高度:2.75快速眼动; text-align:中心; 颜色:# fff; 背景:rgba(90,92,105,0.5); 行高:46 px; }

这可以,也可能应该使用refs来处理:

“…你可以使用ReactDOM。findDOMNode作为一个“逃生舱口”,但我们不推荐它,因为它破坏了封装,在几乎所有情况下,在React模型中都有更清晰的方式来构建代码。”

示例代码:

class MyComponent extends React.Component {
    componentDidMount() {
        this._div.scrollTop = 0
    }

    render() {
        return <div ref={(ref) => this._div = ref} />
    }
}