当它出现在 React.js 中时如何将模态滚动设置为顶部 [英] How to set modal scroll to top when it appears in React.js

查看:53
本文介绍了当它出现在 React.js 中时如何将模态滚动设置为顶部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这是简单的代码

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

推荐答案

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

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.

例如,对您的组件进行以下添加/调整应该可以满足您的需求:

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

这篇关于当它出现在 React.js 中时如何将模态滚动设置为顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆