在react.js中渲染后滚动到页面顶部

滚动 React.js

前端MandyJinJin

2020-03-11

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

第694篇《在react.js中渲染后滚动到页面顶部》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

11个回答
菏以飘落 2020.03.11

如果我假设您要渲染一章,例如每页一本书,那么您要做的就是将其添加到代码中。这对我来说就像魔术一样。

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

这样,您就无需在要渲染的组件上创建引用。

Eva西里蛋蛋 2020.03.11

所有解决方案都涉及在DOM componentDidMountcomponentDidUpdate与DOM一起添加滚动条

我做了所有这些,但没有成功。

因此,想出了一些对我来说很好的方法。

componentDidUpdate() { window.scrollTo(0, 0) } 在标题上添加 的是,该<Switch></Switch>元素不在元素中。在应用程序中免费。作品。

我还发现了一些ScrollRestoration的内容,但是现在我很懒。现在,将其保留为“ DidUpdate”方式。

希望能帮助到你!

注意安全

Jim小哥GO 2020.03.11

这样的事情对我来说对一个组件起作用:

<div ref="scroller" style={{height: 500, overflowX: "hidden", overflowY: "auto"}}>
      //Content Here
</div>

然后在处理更新的任何函数中:

this.refs.scroller.scrollTop=0
村村老丝 2020.03.11

我遇到了一个问题,那就是用Gatsby构建一个站点,该站点的链接建立在Reach Router的顶部。这是必须进行的修改而不是默认行为,这似乎很奇怪。

无论如何,我尝试了上面的许多解决方案,唯一对我有用的解决方案是:

document.getElementById("WhateverIdYouWantToScrollTo").scrollIntoView()

我将其放在useEffect中,但您也可以将其轻松放入componentDidMount或以任何其他方式触发它。

不知道为什么window.scrollTo(0,0)对我(和其他人)不起作用。

神奇古一 2020.03.11

如果您是针对移动设备(至少使用Chrome浏览器)进行此操作,则底部会显示一个白色栏。

URL栏消失时,会发生这种情况。解:

将css的height / min-height:100%更改为height / min-height:100vh

Google开发人员文档

卡卡西理查德 2020.03.11

挂钩解决方案

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

古一蛋蛋 2020.03.11

这是唯一对我有用的东西(带有ES6类组件):

componentDidMount() {
  ReactDOM.findDOMNode(this).scrollIntoView();
}
阿飞小小 2020.03.11

这可以并且可能应该使用refs处理

“ ...您可以将ReactDOM.findDOMNode用作“逃生舱口”,但我们不建议这样做,因为它破坏了封装,并且在几乎每种情况下,都有一种更清晰的方法可以在React模型中构造代码。

示例代码:

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

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

在React Routing中,存在一个问题,如果我们重定向到新路由,那么它将不会自动将您带到页面顶部。

即使我也有同样的问题。

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

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

参考:反应训练

前端MandyJinJin 2020.03.11

由于原始解决方案是为react的早期版本提供的,因此这里进行了更新:

constructor(props) {
    super(props)
    this.myRef = React.createRef()   // Create a ref object 
}

componentDidMount() {
  this.myRef.current.scrollTo(0, 0);
}

render() {
    return <div ref={this.myRef}></div> 
}   // attach the ref property to a dom element
路易飞云 2020.03.11

最后..我用过:

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

编辑:React v16.8 +

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android