我有一个类组件,它有一个onClick
引用内部 ref 的事件处理程序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
在我的事件处理程序中未定义?
编辑 显然代码运行良好,只是不在我的环境中。我将webpack和babel与 env 一起使用,并对带有热重新加载的预设做出反应。我的目标是电子。
完整的错误堆栈:
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)
编辑
想通了,请参阅下面的答案。