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'))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值