代码之家  ›  专栏  ›  技术社区  ›  Nomura Nori

当模式滚动出现在React.js公司

  •  1
  • Nomura Nori  · 技术社区  · 7 年前

    我做了一个模态窗口 react-bootstrap-sweetalert 解放军。 它包含很长的目录,所以我允许 overflow:scroll . 然后滚动到未知位置,所以我需要手动滚动到顶部。

    这是简单的代码

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

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

    1 回复  |  直到 7 年前
        1
  •  1
  •   Dacre Denny    7 年前

    你可以创建一个 ref 到组件中包装可滚动内容的元素,然后使用此引用设置 scrollTop 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>)
    }