react里使用ref的几种方法

Posted on   猫头唔食鱼  阅读(637)  评论(0编辑  收藏  举报

方法一:类似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);
    }

 

 
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示