简体   繁体   English

如何将模式滚动显示在React.js中的顶部

[英]How to set modal scroll to top when it appears in React.js

I made a modal windows using react-bootstrap-sweetalert lib. 我使用react-bootstrap-sweetalert lib创建了一个模态窗口。 It contains long list of contents, so I allowed overflow:scroll . 它包含很长的内容列表,因此我允许overflow:scroll What the problem is, when modal open, it doesn't scroll to top. 问题是,当模式打开时,它不会滚动到顶部。 And scroll to unknown position, so I need to scroll to top manually. 并滚动到未知位置,所以我需要手动滚动到顶部。

This is simple code 这是简单的代码

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

Any advice will be big help for me. 任何建议对我都会有很大帮助。 Thanks 谢谢

You could create a ref to an element in your component that wraps the scrollable content, and then use this ref to set scrollTop to 0 of the corresponding DOM element, when content is displayed in your modal. 您可以在包装可滚动内容的组件中创建对元素的ref ,然后在模式中显示内容时使用此引用将相应DOM元素的scrollTop设置为0

So for instance, the following additions/adjustments to your component should achieve what you need: 因此,例如,对组件进行以下添加/调整应可实现所需的功能:

// 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>)
}

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

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