如何在React.js中显示模态滚动到顶部

问题描述 投票:1回答:1

我使用react-bootstrap-sweetalert lib制作了一个模态窗口。它包含很长的内容列表,所以我允许overflow:scroll。问题是什么,当模态打开时,它不会滚动到顶部。并滚动到未知位置,所以我需要手动滚动到顶部。

这是简单的代码

basicAlert = () => {
   this.setState({
        alert: (
          <div>
           // long list table
          </div>)
   });
}
hideAlert = () => {
   this.setState({
      alert: null
   });
}
render() {
   return (
     {this.state.alert}
     // rest contents ...
   )
}

任何建议对我都有很大的帮助。谢谢

javascript reactjs scroll modal-dialog
1个回答
0
投票

你可以创建一个ref到你的组件中包含可滚动内容的元素,然后使用这个引用将scrollTop设置为相应DOM元素的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>)
}
© www.soinside.com 2019 - 2024. All rights reserved.