初识React(4):ref属性

发布时间:2019-07-01 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了初识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标签,类组件添加,但是不能给函数组件添加

脚本宝典总结

以上是脚本宝典为你收集整理的初识React(4):ref属性全部内容,希望文章能够帮你解决初识React(4):ref属性所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:HTML