react中如何实现ref获取dom或者组件?

AI 概述
react 中 ref 获取 dom 或者组件方法使用 ref 获取 DOM 的引用使用 ref 获取组件的引用react 中的三种 ref 获取 DOM 节点第一种 ref 字符串方式获取 Dom 节点方式第二种 回调式获取 Dom 节点方式第三种 回调式获取 Dom 节点方式 挂在到自身实例 react 中 ref 获取 dom 或者组件方法 使用 ref 获取 DOM ...
目录
文章目录隐藏
  1. react 中 ref 获取 dom 或者组件方法
  2. react 中的三种 ref 获取 DOM 节点

react 中 ref 获取 dom 或者组件方法

使用 ref 获取 DOM 的引用

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

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

为元素添加 ref 引用

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

在页面上获取元素:

this.refs.test

使用 ref 获取组件的引用

为组件添加 ref 引用:

<Text ref="hellow"/>

在页面上使用组件的引用:

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'))

以上就是 react 中 ref 获取 dom 或者组件如何实现的简略介绍,当然详细使用上面的不同还得要大家自己使用过才领会。

以上关于react中如何实现ref获取dom或者组件?的文章就介绍到这了,更多相关内容请搜索码云笔记以前的文章或继续浏览下面的相关文章,希望大家以后多多支持码云笔记。

「点点赞赏,手留余香」

0

给作者打赏,鼓励TA抓紧创作!

微信微信 支付宝支付宝

还没有人赞赏,快来当第一个赞赏的人吧!

声明:本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若内容造成侵权/违法违规/事实不符,请将相关资料发送至 admin@mybj123.com 进行投诉反馈,一经查实,立即处理!
重要:如软件存在付费、会员、充值等,均属软件开发者或所属公司行为,与本站无关,网友需自行判断
码云笔记 » react中如何实现ref获取dom或者组件?

发表回复