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);
        }
     
  • 相关阅读:
    string
    auto和decltype
    const限定符
    &(引用) 和 *(指针)
    extern关键字
    关于将函数写入头文件问题(分离式编译)
    poj2154(polya定理+欧拉函数)
    bzoj2115(线性基)
    51nod1832(二叉树/高精度模板+dfs)
    51nod1464(trie + dfs)
  • 原文地址:https://www.cnblogs.com/luguankun/p/13789701.html
Copyright © 2011-2022 走看看