我有一个类组件,它有一个引用内部引用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
修改
想出来,请看下面的答案。
答案 0 :(得分:1)
想出来,这是react-hot-loader
的一个问题。显然保存this
的值在react-hot-loader
的构造函数中不起作用。修复方法是手动启用babelrc中的transform-es2015-classes
插件。
答案 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是否设置 - 但你可以忽略那部分(通常)。