[英]Uncaught ReferenceError: handleClick is not defined - React
我会直截了当地说。 这是我在ReactJS应用程序中的组件:
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>
);
}
}
为什么在加载组件时会出现以下错误?
Uncaught ReferenceError: handleClick is not defined
编辑:
你回答后我改变了我的代码:
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>
);
}
如你所见,我有.map
,它遍历一系列书籍。 对于每本书,我都有一个按钮,如果单击该按钮,则会将特定的书添加到用户的购物车中。
如果我关注@Tharaka Wijebandara回答我可以在外面制作一个按钮.map
但在这种情况下我仍然得到错误:
Uncaught (in promise) TypeError: Cannot read property 'handleClick' of undefined
at http://localhost:8080/bundle.js:41331:89
at Array.map (native)
使用this.handleClick
<a className="btn btn-success" onClick={this.handleClick}>
Add to cart
</a>
并且您忘记在handleClick
方法中添加e
作为参数。
handleClick(e) {
e.preventDefault();
console.log("The link was clicked");
}
您在编辑部分中提到的问题的解决方案。
原因是,你在map
回调函数中丢失了context
,你需要用回调函数或使用arrow function
bind
这个(类上下文),它将解决你的问题。
通过使用箭头功能 :
renderBooks(){
return this.props.myBooks.data.map((book) => { //here
return (
.....
);
});
}
或者使用.bind(this)
和回调函数,如下所示:
renderBooks(){
return this.props.myBooks.data.map(function (book) {
return (
.....
);
}.bind(this)); //here
}
添加到@Tharaka Wijebandara答案,您也可以将函数声明为const
,如下所示:
render() {
const handleClick = this.handleClick;
return (
<div>
<a className="btn btn-success" onClick={handleClick}>
Add to cart
</a>
</div>
);
}
其中handleClick
定义为:
handleClick(e) {
e.preventDefault();
console.log("The link was clicked");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.