当前位置: 移动技术网 > IT编程>开发语言>JavaScript > React之设置元素的滚动条

React之设置元素的滚动条

2018年11月11日  | 移动技术网IT编程  | 我要评论

       在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;

       }

      

                 

      

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网