初识React(4):ref属性

ref属性其实就是为了获取DOM节点,例如:

import React from 'react'

class RefComponent extends React.Component {
  componentDidMount(){
     this.inputNode.focus();
  }
   render() {
     return (
       <div>
          <h1>ref属性</h1>
          <input type="text" ref={node => this.inputNode = node}/>
       </div>
     )
   }
}

export default RefComponent;

利用ref属性返回的回调函数获取DOM节点,从而让页面渲染完成之后,input聚焦,ref除了可以绑定回调函数之外还能绑定字符串,但是在后期react对字符串形式不再维护,这里就不具体说明了,就用回调函数获取DOM。

除了给input聚焦之外,还可以获取当前DOM节点的内容,如下:

import React from 'react'

class RefComponent extends React.Component {
  componentDidMount(){
     this.inputNode.focus();
     console.log(this.texthtml);
     console.log(this.texthtml.innerHTML);
  }
   render() {
     return (
       <div>
          <h1>ref属性</h1>
          <input type="text" ref={node => this.inputNode = node}/>
          <div ref={node => this.texthtml = node}>你好</div>
       </div>
     )
   }
}

export default RefComponent;

输出结果为:

<div>你好</div>
你好

在这里,我们也发现一个问题,ref虽然获取DOM节点很方便,但是如果ref用的多了,后期就不好维护了,所以,尽量能少用即少用。

ref除了可以给HTML标签添加,也可以给组件添加,例如:

import React from 'react'
import Button from './button.js'

class RefComponent extends React.Component {
  componentDidMount(){
     this.inputNode.focus();
     console.log(this.texthtml);
     console.log(this.texthtml.innerHTML);
     console.log(this.buttonNode);
  }
   render() {
     return (
       <div>
          <h1>ref属性</h1>
          <input type="text" ref={node => this.inputNode = node}/>
          <div ref={node => this.texthtml = node}>你好</div>
          <Button ref={button => this.buttonNode = button}/>
       </div>
     )
   }
}

export default RefComponent;

但是此时,this.buttonNode得到的是一个Button这个组件实例DOM

这里要注意一个问题,ref只能用在类定义的组件,不能用在函数组件,因为函数组件没有实例,比如以下写法就是错误的:

import React from 'react'

function TestComponent() {
   return (
    <div>函数组件</div>
   );
}

class RefComponent extends React.Component {
  componentDidMount(){
     console.log(this.testCom);
  }
   render() {
     return (
       <div>
          <h2>函数组件</h2>
          <TestComponent ref={node => this.testCom = node}/>
       </div>
     )
   }
}

export default RefComponent;

如果这样写,则会报错,并且this.testCom为undefined,因为此时是获取不到函数组件的实例的,所以以上写法要注意

总结: ref可以给HTML标签,类组件添加,但是不能给函数组件添加

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值