import React, { PureComponent,createRef} from 'react'
import HelloWorld from './HelloWorld';
import GetComponent from './Fun';
export default class App extends PureComponent {
constructor(){
super()
this.h2Ref = createRef()
this.componentRef = createRef()
this.h2elRef = null
this.FunRef = createRef()
}
getNativeDom(){
//第一种获取DOM的方式 在react元素上绑定ref字符串
console.log(this.refs.why);
// 2.提前创建好REf 保存在current里面 this.h2Ref = createRef() 最常用
console.log(this.h2Ref.current);
//3.利用h回调函数 拿到对应的元素,并且做一个保存
console.log(this.h2elRef);
//获取类组件的DOM
console.log(this.componentRef.current);
//获取函数组件JSX元素里面的DOM
console.log(this.FunRef.current);
}
render() {
return (
<div>
<h2 ref="why">hello world</h2>
<h2 ref={this.h2Ref}>hello react</h2>
<h2 ref={el=>{this.h2elRef = el}}>hello codewhy</h2>
<HelloWorld ref={this.componentRef}/>
<GetComponent ref={this.FunRef}/>
<button onClick={e=>this.getNativeDom()}>获取DOM</button>
</div>
)
}
}
import { forwardRef } from "react"
const GetComponent = forwardRef(function GetComponent(props,ref){
return(
<div>
<h2 ref={ref}>hello Function</h2>
<button>按钮</button>
</div>
)
})
export default GetComponent
import React, { PureComponent } from 'react'
export default class HelloWorld extends PureComponent {
render() {
return (
<div>HelloWorld</div>
)
}
}