zoukankan      html  css  js  c++  java
  • react里使用ref的几种方法

    方法一:类似vue的写法,标签里定义一个$ref ,然后通过this.refs.xxx获取dom

      {/* 方法一:类似vue的写法 */}
                    <span ref="test">test</span>
     // 获取ref只能在componentDidMount里
        componentDidMount(){
            console.log(this.refs.test); // 这里不是$refs啊,没有$的,vue的才有
        }

    方法二:

     {/* 方法二:xxx=>this.yyy=xxx */}
                    <span ref={test2=>this.haha=test2}>test2</span>
      // 获取ref只能在componentDidMount里
        componentDidMount(){
       console.log(this.haha);
        }
    方法三:接收React.createRef()的值
     {/* 方法三:接收React.createRef*()的值 */}
                    <span ref={this.test3}>test3</span>

    在constructor里使用React.createRef

    constructor(props) {
            super(props);
            // React.createRef()
            this.test3 = React.createRef()
            this.state = {  }
        }

    要用current访问dom

       // 获取ref只能在componentDidMount里
        componentDidMount(){
            console.log(this.haha);
        }
     
  • 相关阅读:
    结构型模式上
    创建型模式下
    创建型模式中
    创建型模式上
    设计模式总述
    Java中事件机制
    UI常用控件
    UITextField和UIViewConteoller
    UIScrollView 和 UIPageControl
    分栏视图控制器
  • 原文地址:https://www.cnblogs.com/luguankun/p/13789701.html
Copyright © 2011-2022 走看看