zoukankan      html  css  js  c++  java
  • React之设置元素的滚动条

           在React中,解耦了对DOM元素的操作,但有时我们确实需要对DOM操作,比如设置元素的滚动条,这时ref就满足了我们的需求

           在低版本的react中,ref可以是一个string类型的属性,通过this.refs.[refString]来获取相应的DOM元素,但在高版本的react中已被弃用

           在高版本中的ref可以是React.createRef()创建ref属性 ,也可以是回调函数,我们可以在构造函数中使用React.createRef()来创建一个ref属性

           例如:   this.testRef = React.createRef(); // 创建ref属性

                     <div ref={this.testRef} />  //将创建的ref属性作为一个元素的ref

                     this.testRef.current //获取元素

            ref 的更新会发生在componentDidMount 或 componentDidUpdate 生命周期钩子之前,所以我们可以在componentDidMount 或 componentDidUpdate中处理业务需求

          注意:不能在函数式组件上使用 ref 属性,因为它们没有实例,但可以在函数式组件内部使用ref

          虽然不能在函数式组件上直接使用ref,但我们可以像组件之间传递参数一样来传递ref

          例如:  render() {

                     const TestRefFunc = (props) => {

                         return (

                             <div ref={props.testRef}>

                         );

                      }

                        return (

                          <TestRefFunc  testRef={(el) => this.testRefEle = el} />

                        );

                    }

            知道了在react中如何获取DOM元素,那么就可以对DOM元素操作,设置元素的滚动条,代码如下

            componentDidMount() {   // 进入组件

                this.testRefEle.current.scrollTop = this.testRefEle.current.scrollHeight;

            }

            componentUpdateMount() {  // 刷新组件

               this.testRefEle.current.scrollTop = this.testRefEle.current.scrollHeight;

           }

          

                     

          

  • 相关阅读:
    详细介绍Linux shell脚本基础学习(二)
    MySQL主从复制
    推荐一款好用的jquery弹出层插件——wbox
    Jenkins安装插件下载失败
    如何在 Amazon RDS 中部署 MySQL 数据库实例
    VMware vSphere 6 Enterprise Plus 永久激活许可证亲测可用
    使用 convert database 命令进行 RMAN 跨平台迁移(12C>19C)
    hbase用户授权
    hbase move region
    hbase表集群间数据同步 hbase replication
  • 原文地址:https://www.cnblogs.com/yezi-dream/p/9941154.html
Copyright © 2011-2022 走看看