最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to set modal scroll to top when it appears in React.js - Stack Overflow

programmeradmin0浏览0评论

I made a modal windows using react-bootstrap-sweetalert lib. It contains long list of contents, so I allowed 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

I made a modal windows using react-bootstrap-sweetalert lib. It contains long list of contents, so I allowed 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

Share Improve this question asked Sep 7, 2018 at 4:33 Nomura NoriNomura Nori 5,1979 gold badges56 silver badges91 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 2

You could create a ref to an element in your ponent 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.

So for instance, the following additions/adjustments to your ponent should achieve what you need:

// Add a constructor to create the ref
constructor(props) {
  super(props)
  // Add a ponent ref to your ponent. You'll use this to set scroll 
  // position of div wrapping content
  this.ponentRef = 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.ponentRef.current.scrollTop = 0;
    });
}

render() {

  // Register your ref with wrapper div
  return (<div ref={ this.ponentRef }>
    { this.state.alert }
    // rest contents ...
    </div>)
}
发布评论

评论列表(0)

  1. 暂无评论