我们先看一下使用示例,然后再解释原理。代码如下:
import React,{PureComponent,createRef} from "react";
class HelloWorld extends PureComponent{
test(){
console.log("test-------")
}
render(){
return <h1>Hello World</h1>
}
}
export class App extends PureComponent{
constructor(){
super()
this.hwRef = createRef()
}
getComponent(){
console.log(this.hwRef.current)
this.hwRef.current.test()
}
render(){
return (
<div>
<HelloWorld ref={this.hwRef}></HelloWorld>
<button onClick={e => this.getComponent()}>获取组件实例</button>
</div>
)
}
}
export default App
上面代码中,我们通过createRef()
创建了一个ref引用对象,并将其赋值给this.hwRef
。然后在HelloWorld
组件上使用<HelloWorld ref={this.hwRef}></HelloWorld>
将这个引用传递给子组件。 这就是直接通过ref获取子组件实例的方法。最后我们附上浏览器中运行结果:
感谢您的观看,我们下次再见!
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我