React中如何使用ref


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

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

字符串方法:

字符串方法

changText(){ this.refs.titleRef.innerHTML = "官方已经不推荐使用了" //使用refs.titleRef拿到当前元素
  }

对象方法:

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

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

this.titleRef}>对象方法

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

函数方法:

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

this.titleEl = arg}>函数方法

//标准模板 changText(){ this.titleEl.innerHTML = '函数的使用方法' }