Javascript 如何在React.js中显示模式滚动时将其设置为顶部

Javascript 如何在React.js中显示模式滚动时将其设置为顶部,javascript,reactjs,scroll,modal-dialog,Javascript,Reactjs,Scroll,Modal Dialog,我使用react引导sweetalertlib创建了一个模式窗口。 它包含很长的内容列表,因此我允许溢出:滚动。 问题是,当模态打开时,它不会滚动到顶部。 然后滚动到未知位置,所以我需要手动滚动到顶部 这是一个简单的代码 basicAlert = () => { this.setState({ alert: ( <div> // long list table </div>)

我使用
react引导sweetalert
lib创建了一个模式窗口。 它包含很长的内容列表,因此我允许
溢出:滚动
。
问题是,当模态打开时,它不会滚动到顶部。
然后滚动到未知位置,所以我需要手动滚动到顶部

这是一个简单的代码

basicAlert = () => {
   this.setState({
        alert: (
          <div>
           // long list table
          </div>)
   });
}
hideAlert = () => {
   this.setState({
      alert: null
   });
}
render() {
   return (
     {this.state.alert}
     // rest contents ...
   )
}
basicAlert=()=>{
这是我的国家({
警报:(
//长列表表
)
});
}
hideAlert=()=>{
这是我的国家({
警报:空
});
}
render(){
返回(
{this.state.alert}
//其余内容。。。
)
}
任何建议都会对我大有帮助。
感谢

您可以为组件中包装可滚动内容的元素创建一个
ref
,然后当内容显示在模式中时,使用此ref将相应DOM元素的
scrollTop
设置为
0

因此,例如,对组件的以下添加/调整应满足您的需要:

// Add a constructor to create the ref
constructor(props) {
  super(props)
  // Add a component ref to your component. You'll use this to set scroll 
  // position of div wrapping content
  this.componentRef = React.createRef();

}

basicAlert = () => {
  this.setState({
    alert: (
      <div>
      // long list table
      </div>)
     }, () => {

      // After state has been updated, set scroll position of wrapped div
      // to scroll to top
      this.componentRef.current.scrollTop = 0;
    });
}

render() {

  // Register your ref with wrapper div
  return (<div ref={ this.componentRef }>
    { this.state.alert }
    // rest contents ...
    </div>)
}
//添加构造函数以创建引用
建造师(道具){
超级(道具)
//向组件添加组件引用。您将使用此选项设置滚动
//div包装内容的位置
this.componentRef=React.createRef();
}
basicAlert=()=>{
这是我的国家({
警报:(
//长列表表
)
}, () => {
//更新状态后,设置已包装div的滚动位置
//滚动到顶部
this.componentRef.current.scrollTop=0;
});
}
render(){
//向wrapper div注册您的ref
返回(
{this.state.alert}
//其余内容。。。
)
}