gpt4 book ai didi

javascript - Uncaught ReferenceError : handleClick is not defined - React

转载 作者:行者123 更新时间:2023-12-03 23:20:57 26 4
gpt4 key购买 nike

我会直奔主题。这是我在 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>

你忘了加 e作为您的 handleClick 中的参数方法。
handleClick(e) {
e.preventDefault();
console.log("The link was clicked");
}

关于javascript - Uncaught ReferenceError : handleClick is not defined - React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43488435/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com