spl*_*unk 2 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");
}
render() {
return (
<div>
<a className="btn btn-success" onClick={handleClick}>
Add to cart
</a>
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
为什么在加载组件时会出现以下错误?
Uncaught ReferenceError: handleClick is not defined
Run Code Online (Sandbox Code Playgroud)
编辑:
你回答后我改变了我的代码:
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>
);
}
Run Code Online (Sandbox Code Playgroud)
如你所见,我有.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)
Run Code Online (Sandbox Code Playgroud)
使用 this.handleClick
<a className="btn btn-success" onClick={this.handleClick}>
Add to cart
</a>
Run Code Online (Sandbox Code Playgroud)
而你忘e了在你的handleClick方法中添加一个参数.
handleClick(e) {
e.preventDefault();
console.log("The link was clicked");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6433 次 |
| 最近记录: |