×

react:如何使用ref获取dom或者组件

作者:Terry2023.06.16来源:Web前端之家浏览:2371评论:0
关键词:reactDom节点

今天来了解下在react里,如何使用ref获取dom或者组件,做做一些应用。

使用ref获取DOM的引用

在vue中,如果想获取DOM元素时,可以使用this.$refs.引用名称

在react中也可以像vue中,有类似的写法,如下

为元素添加ref引用

<h2 ref="test">这是h2标签</h2>

在页面上使用组件的引用

this.refs.hellow

注意点: 只要使用ref拿到组件的引用对象,它就是组件的实例对象,因此就可以调用这个组件的方法,或者它的属性

react中的三种ref获取DOM节点

第一种 ref字符串方式获取Dom节点方式

已废弃的原始方法

class Dom extends React.Component{
    showInputDom = () =>{
      const {userNameInput} = this.refs
      console.log(userNameInput);
    }
    render(){
      return (
        <div>
          <input ref="userNameInput" type="text"/>
          <button onClick={this.showInputDom}>点击显示inpuDom</button>
        </div>
      )
    }
  }
  ReactDOM.render(<Dom/>,document.getElementById('root'))

第二种 回调式获取Dom节点方式

开发常用

class Dom extends React.Component{
    showInputDom = () =>{
      const {userNameInput} = this
      console.log(userNameInput);
    }
    render(){
      return (
        <div>
          {/*注释 (currentNode)=>{this.userNameInput =currentNode} 这里边的currentNode 为 当前的node节点 简称c */}
          {/*<input ref={(currentNode)=>{this.userNameInput =currentNode}} type="text"/>*/}
          <input ref={(c)=>{this.userNameInput = c}} type="text"/>
          <button onClick={this.showInputDom}>点击显示inpuDom</button>
        </div>
      )
    }
  }
  ReactDOM.render(<Dom/>,document.getElementById('root'))

第三种 回调式获取Dom节点方式 挂在到自身实例

  class Dom extends React.Component{
    // 挂载到了自身实例上了
    userNameInput= (c) =>{
      this.input1 = c ;
      console.log(c);
    }
    render(){
      return (
        <div>
          {/*会在试图更新时调用两次 第一次赋值为null,第二次赋值为dom节点*/}
          {/*<input ref={(c)=>{this.userNameInput =c}} type="text"/>*/}
          {/*在试图更新时不会调用}
          {/*<input ref={ this.userNameInput } type="text"/>*/}
          {/*注意这俩个方法是有区别的,这两个对项目的影响可以忽略不记*/}
          <input ref={this.userNameInput} type="text"/>
          <button onClick={this.showInputDom}>点击显示inpuDom</button>
        </div>
      )
    }
  }
  ReactDOM.render(<Dom/>,document.getElementById('root'))


您的支持是我们创作的动力!
温馨提示:本文作者系Terry ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://jiangweishan.com/article/react20230616a.html

网友评论文明上网理性发言 已有0人参与

发表评论: