使用ReactJS的es6方法与类中的方法中的'this'关键字的上下文混淆
这给出了一个错误,无法获得未定义的引用
class AddItem extends React.Component {
constructor() {
super();
}
addIt(e) {
e.preventDefault();
let newItem = {
title: this.refs.title.value
}
this.refs.feedForm.reset();
this.props.addItem(newItem);
}
render() {
return (
<div>
<form ref="feedForm" onSubmit={this.addIt}>
<div className="input-group">
<span className="input-group-addon"><strong>Title:</strong></span>
<input ref="title" type="text" className="form-control" />
</div>
<button className="btn btn-success btn-block">Add Item</button>
</form>
</div>
);
}
}
但这似乎工作正常
class AddItem extends React.Component {
constructor() {
super();
this.addIt = function(e) {
e.preventDefault();
let newItem = {
title: this.refs.title.value
}
this.refs.feedForm.reset();
this.props.addItem(newItem);
}.bind(this)
}
render() {
return (
<div>
<form ref="feedForm" onSubmit={this.addIt}>
<div className="input-group">
<span className="input-group-addon"><strong>Title:</strong></span>
<input ref="title" type="text" className="form-control" />
</div>
<button className="btn btn-success btn-block">Add Item</button>
</form>
</div>
);
}
}
在第一个中我做错了什么
答案 0 :(得分:5)
当您使用ES6类创建React组件时,您需要为事件处理程序手动绑定this
,
class AddItem extends React.Component {
constructor() {
super();
}
addIt(e) {
// other code
}
render() {
return <div>
<form ref="feedForm" onSubmit={this.addIt.bind(this)}>
// other code
</form>
</div>
}
}
或更好地设置this
中的constructor
,
class AddItem extends React.Component {
constructor() {
super();
this.addIt = this.addIt.bind(this);
}
// other code
}