首页 > 解决方案 > 获取类组件中事件的反应参考值的正确方法是什么?

问题描述

在类 Component 中获取事件的 react ref 值的权利是什么?

class ReactRef extends Component {
  constructor(props) {
    super(props);
    this.buttonValue = React.createRef();
  }


  hasText() {
    console.log(this.buttonValue.current); //Cannot read property 'buttonValue' of undefined
  }


  render(){
   return(
     <div>
      <button type="text" ref={this.buttonValue} onClick={this.hasText}> Click me </button>
     </div>
    )
   }

 }

标签: reactjs

解决方案


您需要绑定hasText到正确的范围。

您可以使用箭头函数声明它 -

hasText = () => {
  // now you have access to this.buttonValue.current
}

或者你可以在你的构造函数中绑定它 -

constructor(props) {
  super(props);
  this.buttonValue = React.createRef();
  this.hasText = this.hasText.bind(this);
}

推荐阅读