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

标签 javascript reactjs scroll modal-dialog

我使用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 ...
   )
}

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

最佳答案

您可以在包装可滚动内容的组件中的元素上创建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>)
}

关于javascript - 如何将模式滚动显示在React.js中的顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52215348/

相关文章:

javascript - Radium 内联 CSS - 构建导出类?

javascript - React Router 6 中的搜索参数

android - 使用 SuperSLiM 库检测 RecyclerView 的 GridLayoutManager 滚动结束

javascript - 在 IE < 9 上使用 addEventListener 的最佳方法

javascript - 在 React 中为 JSX 组件添加过渡效果

ios - 修复了 UIPageViewController 的背景滚动效果

javascript - ReactJS 网络应用程序 : Selective Mobile Scrolling Bug

javascript - JS 在第一次访问时重定向到启动页面?

javascript - TranslateZ 百分比 CSS 3D 变换

javascript - 使用 Javascript 添加订单项时如何处理 HTML 元素 ID 和 Javascript 引用?