Desplácese hasta la parte superior de la página después de renderizar en react.js

Resuelto Andrew Kovalenko asked hace 8 años • 40 respuestas

Tengo un problema, que no tengo idea de cómo solucionarlo. En mi componente de reacción muestro una larga lista de datos y algunos enlaces en la parte inferior. Después de hacer clic en cualquiera de estos enlaces, completo la lista con una nueva colección de enlaces y necesito desplazarme hasta la parte superior.

El problema es: ¿cómo desplazarse hasta la parte superior después de representar la nueva colección?

'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;
Andrew Kovalenko avatar Oct 17 '15 23:10 Andrew Kovalenko
Aceptado

Finalmente... usé:

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

EDITAR: Reaccionar v16.8+

useEffect(() => {
  window.scrollTo(0, 0)
}, [])
sledgeweight avatar Sep 06 '2016 09:09 sledgeweight

Dado que la solución original se proporcionó para una versión muy temprana de reaccionar , aquí hay una actualización:

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
Andrew Kovalenko avatar Oct 19 '2015 00:10 Andrew Kovalenko

Podrías usar algo como esto. ReactDom es para reaccionar.14. Simplemente reacciona de otra manera.

    componentDidUpdate = () => { ReactDom.findDOMNode(this).scrollIntoView(); }

Actualización 11/05/2019 para React 16+

  constructor(props) {
    super(props)
    this.childDiv = React.createRef()
  }

  componentDidMount = () => this.handleScroll()

  componentDidUpdate = () => this.handleScroll()

  handleScroll = () => {
    const { index, selected } = this.props
    if (index === selected) {
      setTimeout(() => {
        this.childDiv.current.scrollIntoView({ behavior: 'smooth' })
      }, 500)
    }
  }
Expandir fragmento

J. Mark Stevens avatar Oct 17 '2015 17:10 J. Mark Stevens

Solución de gancho :

  • Crear un gancho 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);

  • Envuelve tu aplicación con ella

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

Documentación: https://reacttraining.com/react-router/web/guides/scroll-restoration

Quentin C avatar Oct 02 '2019 13:10 Quentin C