react ref

时间:2022-05-27 19:43:49   收藏:0   阅读:5

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

例如下面代码:

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;

原文:https://www.cnblogs.com/1024L/p/15353894.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!