我们先看一下使用示例,然后再解释原理。代码如下:
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获取子组件实例的方法。最后我们附上浏览器中运行结果:
感谢您的观看,我们下次再见!
@十二使徒岩 哪张图片?
照片令人惊艳。继续保持 心情。
新年快乐!
十天看一部剧,还可以吧
@梦不见的梦 行,谢谢提醒,我优化一下
网站的速度有待提升,每次打开都要转半天还进不来呢
@React实战爱彼迎项目(二) - 程序员鸡皮 哪里有问题了,报错了吗?
@Teacher Du 那是怕你们毕不了业,我大学那会儿给小礼品
我们大学那会,献血还给学分~
@ab 我想去学网安,比如网警,但分也贼高😕