简体   繁体   English

事件发生后如何使用React滚动到某个元素?

[英]How to scroll to an element using React after an event?

I'm new using React and I have built these little code. 我是使用React的新手,并且已经构建了这些小代码。 Basically, it shows a list of persons after a button's click but when the list is shown, the scroll stays at top of screen and I want that it scrolls down until the element 'section' 基本上,它显示了单击按钮后的人员列表,但是当显示该列表时,滚动条停留在屏幕顶部,我希望它向下滚动直到元素“ section”

 import React, { Component } from 'react';
 import logo from './logo.svg';
 import './App.css';
 import'./Person/Person.css';
 import Person from './Person/Person';

 class App extends Component {

   state = {
     persons: [
       {name:'Carlos', age:24},
       {name:'Liliana', age:20},
       {name:'Max', age:24}
     ],

     showPersons: false
   }


   togglePersonsHandle = () => {
     const doesShow = this.state.showPersons;
     this.setState( 
       { showPersons : !doesShow}
     );   

     /****************************************************/
     /* Here is where I want the window gets scroll down*/
     /****************************************************/
     if(!doesShow)
     {
       this.scrollToMyRef();
     }
   }

   // My method for scrolling
   scrollToMyRef = () => { 
     window.scrollTo({
         top: this.myRef.offsetTop, 
         behavior: "smooth"
     })
 }

   render() {

     let persons = null;
     if(this.state.showPersons)
     {
       persons = 
       (
         <div>
           {this.state.persons.map(person => 
               { return <Person 
                          name = {person.name} 
                          age = {person.age} >
                        </Person>
               }
             )
           }          
         </div>
       );
     }



     return (
       <div className="App">
         <header className="App-header">
           <img src={logo} className="App-logo" alt="logo" />
           <p>
             Edit <code>src/App.js</code> and save to reload.
           </p>
           <a
             className="App-link"
             href="https://reactjs.org"
             target="_blank"
             rel="noopener noreferrer"
           >
             Learn React
           </a>          
         </header>   


         /************    My reference   *****************/ 
         <section ref={ el => this.myRef = el }>

         <button onClick={this.togglePersonsHandle}>
            Click me to toggle 
         </button>

         {persons}
         </section>   
       </div>    
     );

   }
 }

 export default App;

I tried setting the property showPersons = true and use the button's clicked event just for scroll down, and it works! 我尝试设置属性showPersons = true,并仅将按钮的clicked事件用于向下滚动,所以它起作用了! But when I use the button's clicked event for toggle the list of persons, the scroll stays at top all the time. 但是,当我使用按钮的clicked事件来切换人员列表时,滚动始终保持在顶部。

I hope someone can help me! 我希望有一个人可以帮助我!

If I understand correctly, in you togglePersonsHandle , you're asking React to modify the dom & run scrollTo at the same time. 如果我理解正确的话,在您togglePersonsHandle ,您要求React修改dom并同时运行scrollTo。 When the dom renders, it cancels scrollTo. dom渲染时,它将取消scrollTo。

I can think of 2 ways to recover from this: 我可以想到两种从中恢复的方法:

Let the dom breathe 让dom呼吸

Wrap your scrollTo code inside a setTimeout with 0 duration. 将您的scrollTo代码包装在持续时间为0的setTimeout中。 This schedule the function to run after render(). 这样可以安排函数在render()之后运行。

  togglePersonsHandle = () => {
  ...

  if (!this.state.showPersons) {
+   setTimeout(() => {
      this.scrollToMyRef();
+   }, 0)
  }

Do it in componentDidUpdate 在componentDidUpdate中做

I think this is more react-y, also your intention is clearer: once the persons are shown, scroll to that section, however you lose some control over this (other state change might trigger scroll) 我认为这更具反应性,您的意图也更明确:显示人员之后,滚动到该部分,但是您对此失去控制(其他状态更改可能会触发滚动)

+ componentDidUpdate() {
+ // at this point, state's already updated
+   if (this.state.showPersons) {
+     this.scrollToMyRef();
+   }
+ }

Hope it helps! 希望能帮助到你!

Cool buddy it will help you. 帅哥,它将为您提供帮助。

const scrollToDiv=()=>{
document.getElementById('afterEventTrigger').scrollIntoView(true);
}
<div>
<button onClick={this.scrollToDiv}></button>
<div id='afterEventTrigger'>

</div>
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM