之前我们已经讲过了如何获取类组件实例,那么如何获取函数组件的DOM呢?
原理
我们可以通过forwardRef
将函数组件转化为类组件,然后通过createRef
创建ref引用对象,最后将ref引用对象传递给函数组件。
案例代码
import React,{PureComponent,createRef,forwardRef} from "react";
const HelloWorld = forwardRef(function(props,ref){
return (
<div>
<h1 ref={ref}>Hello World</h1>
<p>哈哈哈</p>
</div>
)
})
export class App extends PureComponent{
constructor(){
super()
this.hwRef = createRef()
}
getComponent(){
console.log(this.hwRef.current)
}
render(){
return (
<div>
<HelloWorld ref={this.hwRef}></HelloWorld>
<button onClick={e=>this.getComponent()}>获取组件实例</button>
</div>
)
}
}
export default App
注意事项
- 函数组件必须使用
forwardRef
进行转化 - 函数组件必须使用
ref
接收ref引用对象 - 函数组件必须使用
current
获取DOM
最后,我们来看一下运行结果:
感谢您的观看,我们下次再见!
of course like your web site but you need to test the spelling on quite a few of your posts. A number of them are rife with spelling problems and I in finding it very troublesome to inform the reality nevertheless I will surely come again again.
新年快乐!
十天看一部剧,还可以吧
@梦不见的梦 行,谢谢提醒,我优化一下
网站的速度有待提升,每次打开都要转半天还进不来呢
@React实战爱彼迎项目(二) - 程序员鸡皮 哪里有问题了,报错了吗?
@Teacher Du 那是怕你们毕不了业,我大学那会儿给小礼品
我们大学那会,献血还给学分~
@ab 我想去学网安,比如网警,但分也贼高😕
@夜 加油,你一样也可以成为程序员的,需要学习资料可以V我