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

React - Can't access refs in stateful component event handler

我有一个 class 组件,它有一个 onClick 事件处理程序,它引用了一个内部引用 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>
    );
  }
}

为什么 this.input 在我的事件处理程序中未定义?

编辑 显然代码运行良好,只是不在我的环境中。我正在将 webpackbabel 与 env 和 react 预设一起使用,并进行热重载。我的目标是 electron.

错误堆栈已满:

my-component.jsx:12 Uncaught TypeError: Cannot read property 'click' of undefined
    at MyComponent.onClick (http://localhost:8080/renderer.js:19224:15)
    at Object.ReactErrorUtils.invokeGuardedCallback (webpack:///./node_modules/react-dom/lib/ReactErrorUtils.js?:69:16)
    at executeDispatch (webpack:///./node_modules/react-dom/lib/EventPluginUtils.js?:85:21)
    at Object.executeDispatchesInOrder (webpack:///./node_modules/react-dom/lib/EventPluginUtils.js?:108:5)
    at executeDispatchesAndRelease (webpack:///./node_modules/react-dom/lib/EventPluginHub.js?:43:22)
    at executeDispatchesAndReleaseTopLevel (webpack:///./node_modules/react-dom/lib/EventPluginHub.js?:54:10)
    at Array.forEach (native)
    at forEachAccumulated (webpack:///./node_modules/react-dom/lib/forEachAccumulated.js?:24:9)
    at Object.processEventQueue (webpack:///./node_modules/react-dom/lib/EventPluginHub.js?:254:7)
    at runEventQueueInBatch (webpack:///./node_modules/react-dom/lib/ReactEventEmitterMixin.js?:17:18)

编辑

想通了,请看下面我的回答。

我认为您正在尝试获取输入值。如果是,这里是代码。没有 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;

您是否尝试过将 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 - 但您可以忽略该部分(通常)。

搞清楚了,是react-hot-loader的问题。显然保存 this 的值在带有 react-hot-loader 的构造函数中不起作用。解决方法是在您的 babelrc 中手动启用 transform-es2015-classes 插件。

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