Javascript 如何在事件发生后使用React滚动到元素?
我是使用React的新手,我已经构建了这些小代码。基本上,它显示了一个按钮点击后的人员列表,但当列表显示时,滚动保持在屏幕顶部,我希望它向下滚动,直到元素“部分”Javascript 如何在事件发生后使用React滚动到元素?,javascript,reactjs,Javascript,Reactjs,我是使用React的新手,我已经构建了这些小代码。基本上,它显示了一个按钮点击后的人员列表,但当列表显示时,滚动保持在屏幕顶部,我希望它向下滚动,直到元素“部分” import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import'./Person/Person.css'; import Person from './Person/Person'; c
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;
我试着设置属性showPersons=true,并使用按钮的clicked事件进行向下滚动,效果很好!但是,当我使用按钮的clicked事件切换人员列表时,滚动条始终位于顶部
我希望有人能帮助我 如果我理解正确,在您的
切换PersonHandle
中,您要求React同时修改dom&run scrollTo。当dom呈现时,它会取消滚动
我可以想出两种方法从中恢复过来:
让世界呼吸吧
将scrollTo代码包装在持续时间为0的setTimeout中。这将计划函数在render()之后运行
在componentDidUpdate中执行此操作
我认为这更具反应性,你的意图也更清晰:一旦显示了人物,滚动到该部分,但是你会失去一些控制(其他状态更改可能会触发滚动)
希望有帮助 很酷,伙计,它会帮你的
const scrollToDiv=()=>{
document.getElementById('afterEventTrigger').scrollIntoView(true);
}
+ componentDidUpdate() {
+ // at this point, state's already updated
+ if (this.state.showPersons) {
+ this.scrollToMyRef();
+ }
+ }
const scrollToDiv=()=>{
document.getElementById('afterEventTrigger').scrollIntoView(true);
}