使用ref获取react组件实例

4,751 阅读1分钟

方法 1: 使用refs拿到组件实例

import React from 'react';

class Ref1 extends React.Component{
  componentDidMount(){
    console.log(this.refs['box'],'refs')
    //我是一个盒子组件 refs
  }
  render(){
    return <div ref='box'>我是一个盒子组件</div>
  }
}

方法 2: 使用回调函数

import React from 'react';

class Ref2 extends React.Component{
  componentDidMount(){
    console.log(this.container.innerHTML,'refs')
    //我是一个盒子组件 refs
  }
  render(){
    return <div ref={ box => {this.container = box}}>我是一个盒子组件</div>
  }
}

这种方式与方法一达到的效果是一样的,都是获取其引用;

方法 3:使用React.createRef()

import React from 'react';

class Ref3 extends React.Component{
  constructor(props){
    super(props)
    this.myRef = React.createRef();
  }
  componentDidMount(){
    console.log(this.myRef.current.innerHTML,'refs')
    //我是一个盒子组件 refs
  }
  render(){
    return <div ref={ this.myRef }>我是一个盒子组件</div>
  }
}

React 16.3版本后,使用此方法来创建ref。将其赋值给一个变量,通过ref挂载在dom节点或组件上,该ref的current属性,将能拿到dom节点或组件的实例;