React中如何使用ref

在react中。不建议直接操作DOM元素。

在元素上使用ref,可以传字符串,对象,函数。官方推荐对象

 

字符串方法:

<h2 ref="titleRef">字符串方法</h2>
<button onClick={e=>this.changText()}>改变文本</button>
changText(){
    this.refs.titleRef.innerHTML = "官方已经不推荐使用了"     //使用refs.titleRef拿到当前元素
  }

对象方法:

import React, { PureComponent,createRef } from 'react'  //先导入createRef

this.titleRef  = createRef()   //在构造器中赋值

<h2 ref={this.titleRef}>对象方法</h2> //元素

<button onClick={e=>this.changText()}>改变文本</button>

changText(){
    this.titleRef.current.innerHTML = '官方推荐使用'
  }

函数方法:

this.titleEl = null;   //在构造器中定义一个空

<h2 ref={arg=>this.titleEl = arg}>函数方法</h2> //标准模板

<button onClick={e=>this.changText()}>改变文本</button>

changText(){
  this.titleEl.innerHTML = '函数的使用方法'  
}

 

posted @ 2022-01-16 17:04  无何不可88  阅读(219)  评论(0)    收藏  举报