React - 无法在有状态组件事件处理程序中访问引用

时间:2017-08-21 16:47:22

标签: javascript reactjs events electron refs

我有一个类组件,它有一个引用内部引用onClick的{​​{1}}事件处理程序。但是,在事件处理程序input为空。我将事件处理程序绑定到构造函数中的input

this

为什么import React, { Component} from 'react'; class MyComponent extends Component { constructor(props) { super(props); this.onClick = this.onClick.bind(this); } onClick(e) { // The following throws "Cannot read property 'click' of undefined" this.input.click(); } render() { return ( <div className="container" onClick={this.onClick}> <input type="text" ref={input => this.input = input} /> </div> ); } } 在我的事件处理程序中未定义?

修改 显然代码运行正常,而不是在我的环境中。我正在使用 webpack babel 与env一起使用热重新加载的预设。我的目标是电子

完整错误堆栈:

this.input

修改

想出来,请看下面的答案。

3 个答案:

答案 0 :(得分:1)

想出来,这是react-hot-loader的一个问题。显然保存this的值在react-hot-loader的构造函数中不起作用。修复方法是手动启用babelrc中的transform-es2015-classes插件。

请参阅https://github.com/gaearon/react-hot-loader/issues/597

答案 1 :(得分:0)

我认为你正试图获得投入价值。如果是,这里是代码。没有this.input.click();方法定义

import React from 'react';

class MyComponent extends React.Component {
   constructor(props) {
    super(props);
    this.onClick = this.onClick.bind(this);
  }

  onClick(e) {
    // The following throws "Cannot read property 'click' of undefined"
    console.log(this.input.value);
  }

  render() {
    return (
      <div className="container">
        <input type="text" ref={input => this.input = input} onChange={this.onClick}/>
      </div>
    );
  }
}

export default MyComponent;

答案 2 :(得分:0)

您是否尝试将onClick回调重写为箭头功能?这也会使你的代码变得更小:

import React, { Component } from 'react';

class MyComponent extends Component {
  this.input = null;

  onClick = () => {
    this.input && this.input.click();
  }

  render() {
    return (
      <div className="container" onClick={this.onClick}>
        <input type="text" ref={input => this.input = input} />
      </div>
    );
  }
}

即使它不重要,我也会检查this.input是否设置 - 但你可以忽略那部分(通常)。

相关问题