React ref 获取dom 的方式

124 阅读1分钟

方式1 通过 createRef 进行绑定 方式二 通过 this.refs.twoDom 方式三 在ref 传入函数 直接获取

import { createRef, PureComponent } from 'react';
interface AppState {
 HomeRef: object | undefined | null
}
export class App extends PureComponent {
 HomeRef: any
 getNativeDom() {
     //方式1
   console.log(this.HomeRef.current);
   
   //方式二 
   console.log(this.refs.twoDom)
 }
 constructor(prosp: App) {
   super(prosp)
   this.state = {
     HomeRef: undefined
   } as AppState
   this.HomeRef = createRef()
 }
 render() {
   return (
     <div>
       <h2 className='title' ref={this.HomeRef}>hhhh</h2>
       <h2 ref='twoDom'>hhhh</h2>
       <h2 ref='(e) => { console.log(e) }'>hhhh</h2>
       <button onClick={() => this.getNativeDom()}>获取Dom</button>
     </div>
   )
 }
}

export default App