一. ref 用于HTML标签元素中
<h2 ref=字符串/对象/函数>h2元素<h2>
其中,字符串形式 官方已不再推荐使用
1.对象形式
import React, { Component,createRef } from 'react'
export default class App extends Component {
constructor(){
super();
this.titleRef=createRef();
}
render() {
return (
<div>
<h2 ref={this.titleRef}>App组件内容</h2>
<button onClick={e=>this.btnApp()}>App按钮</button>
</div>
)
}
btnApp(){
this.titleRef.current.innerHTML="改变后的文本"
}
}
2.函数形式
import React, { Component} from 'react'
export default class App extends Component {
constructor(){
super();
this.titleEL=null;
}
render() {
return (
<div>
<h2 ref={(arg)=>this.titleEL=arg}>App组件内容</h2>
<button onClick={e=>this.btnApp()}>App按钮</button>
</div>
)
}
btnApp(){
this.titleEL.innerHTML="11111111"
}
}
二. ref 用于组件上
可以实现:点击父组件中的按钮,调用子组件中的方法
父组件:
import React, { Component, createRef} from 'react'
import Counter from './Counter'
export default class App extends Component {
constructor(){
super();
this.counterRef=createRef()
}
render() {
return (
<div>
<Counter ref={this.counterRef}/>
<button onClick={e=>this.CounterClick()}>App按钮</button>
</div>
)
}
CounterClick(){
this.counterRef.current.CounterClick()
}
}
子组件:
import React, { PureComponent } from 'react'
export default class Counter extends PureComponent {
constructor(){
super();
this.state={
num:0
}
}
render() {
return (
<div>
num:{this.state.num}
<button onClick={e=>this.CounterClick()}>Counter+1</button>
</div>
)
}
CounterClick(){
this.setState({
num:this.state.num+1
})
}
}
注意:当ref用于组件时,current才表示组件对象
若子组件是函数式组件,则无法获取对应的组件对象,因为函数式组件没有实例。函数式组件中不能使用ref获取。要想获取函数式组件的DOM元素,要用React.forwardRef(高阶组件)以及hooks