Javascript 未捕获引用错误:未定义handleClick-反应
我直截了当地说。这是我在ReactJS应用程序中使用的组件:Javascript 未捕获引用错误:未定义handleClick-反应,javascript,reactjs,Javascript,Reactjs,我直截了当地说。这是我在ReactJS应用程序中使用的组件: class BooksList extends Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick() { e.preventDefault(); console.log("The link was clicked");
class BooksList extends Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
e.preventDefault();
console.log("The link was clicked");
}
render() {
return (
<div>
<a className="btn btn-success" onClick={handleClick}>
Add to cart
</a>
</div>
);
}
}
编辑:
您回答后,我将代码更改为:
handleClick(e) {
e.preventDefault();
console.log("Item added to the cart");
}
renderBooks(){
return this.props.myBooks.data.map(function(book){
return (
<div className="row">
<table className="table-responsive">
<tbody>
<tr>
<td>
<p className="bookTitle">{book.title}</p>
</td>
</tr>
<tr>
<td>
<button value={book._id} onClick={this.handleClick}>Add to cart</button>
</td>
</tr>
</tbody>
</table>
</div>
);
});
}
}
render() {
return (
<div>
<div>
<h3>Buy our books</h3>
{this.renderBooks()}
</div>
</div>
);
}
使用
this.handleClick
<a className="btn btn-success" onClick={this.handleClick}>
Add to cart
</a>
添加到@Tharaka Wijebandara answer中,您也可以将函数声明为
const
,如下所示:
render() {
const handleClick = this.handleClick;
return (
<div>
<a className="btn btn-success" onClick={handleClick}>
Add to cart
</a>
</div>
);
}
您在编辑部分中提到的问题的解决方案 原因是,您在
map
回调函数中失去了上下文
,您需要将此(类上下文)绑定到回调函数或使用箭头函数
,这将解决您的问题
通过使用:
或者使用带有回调函数的.bind(this)
,如下所示:
renderBooks(){
return this.props.myBooks.data.map(function (book) {
return (
.....
);
}.bind(this)); //here
}
handleClick(e) {
e.preventDefault();
console.log("The link was clicked");
}
render() {
const handleClick = this.handleClick;
return (
<div>
<a className="btn btn-success" onClick={handleClick}>
Add to cart
</a>
</div>
);
}
handleClick(e) {
e.preventDefault();
console.log("The link was clicked");
}
renderBooks(){
return this.props.myBooks.data.map((book) => { //here
return (
.....
);
});
}
renderBooks(){
return this.props.myBooks.data.map(function (book) {
return (
.....
);
}.bind(this)); //here
}