ref属性可以设置为一个回调函数,这也是官方强烈推荐的用法;这个函数执行的时机为:

  • 组件被挂载后,回调函数被立即执行,回调函数的参数为该组件的具体实例。

  • 组件被卸载或者原有的ref属性本身发生变化时,回调也会被立即执行,此时回调函数参数为null,以确保内存泄露。

例如下面代码:

import React from 'react'

class RegisterStepTwo extends React.Component{
  state = {
    visible: true
  }
  changeVisible(){
    this.setState({visible: !this.state.visible});
  }
  refCb(instance){
    console.log(instance);
  }
  render(){
    return(
      <div>
        <button type="button" onClick={this.changeVisible.bind(this)}>{this.state.visible ? '卸载' : '挂载'}ConfirmPass
        </button>
        {
          this.state.visible ?
            <div ref={this.refCb}/>: null
         }
       </div>
     )
  }
}
export default RegisterStepTwo;
 
使用场景:
import React from 'react'

class NameForm extends React.Component {
    constructor(props) {
      super(props);
      this.state = {value: ''};
    }
   render() {
      return (
          <div>
          <input type="text" ref={el=>this.input =el} placeholder="演出/艺人/场馆"/>      
          <button onClick={this.Searchtitle.bind(this)}>获取</button>
          </div>
      );
    }  
    Searchtitle(){    console.log(this.input.value)  //实时的获取输入框中的值  }
  }
}
export default NameForm;