我有以下代码:
renderPosts() {
return _.map(this.state.catalogue, (catalogue, key) => {
return (
<div className="item col-md-3" key={key} id={key}>
<img src={this.state.catalogue[key].avatarURL} height={150} with={150}/>
<h3>{catalogue.marque}</h3>
<h4>{catalogue.numero}</h4>
<h4>{catalogue.reference}</h4>
<p>{catalogue.cote}</p>
<div className="text-center">
<button className="btn btn-danger" onClick={() => {if(window.confirm('Delete the item?')){this.removeToCollection.bind(this, key)};}}>Supprimer</button>
</div>
</div>
)
})
}
我也有这个功能:
removeToCollection(key, e) {
const item = key;
firebase.database().ref(`catalogue/${item}`).remove();
}
当我在“onclick”按钮中使用没有确认窗口的功能时,代码工作得很好。但是当我想使用确认窗口时,当我点击我的按钮时,确认窗口会显示,但我的项目不会被删除。
任何的想法 ?
谢谢您帮忙 !
基本上你是绑定函数而不是调用它...你应该事先绑定,最好是在构造函数中...然后调用它。试试这个:
renderPosts() {
this.removeToCollection = this.removeToCollection.bind(this);
return _.map(this.state.catalogue, (catalogue, key) => {
return (
<div className="item col-md-3" key={key} id={key}>
<img src={this.state.catalogue[key].avatarURL} height={150} with={150}/>
<h3>{catalogue.marque}</h3>
<h4>{catalogue.numero}</h4>
<h4>{catalogue.reference}</h4>
<p>{catalogue.cote}</p>
<div className="text-center">
<button className="btn btn-danger" onClick={() => {if(window.confirm('Delete the item?')){this.removeToCollection(key, e)};}}>Supprimer</button>
</div>
</div>
)
})
}
你只是绑定功能而不是调用它。
正确的语法使用bind
并称为qazxsw pied函数。
bind
或者你也可以这样做,没有绑定。
if (window.confirm("Delete the item?")) {
let removeToCollection = this.removeToCollection.bind(this, 11);//bind will return to reference to binded function and not call it.
removeToCollection();
}
如果这是if (window.confirm("Delete the item?")) {
this.removeToCollection(11);
}
内部的问题,那么使用removeToCollection
来定义它。
arrow function
工作removeToCollection=(key)=> {
console.log(key);
}
我的做法如下 -
我有一个智能(类)组件
codesandbox demo
我定义了一个函数来调用删除端点 -
<Link to={`#`} onClick={() => {if(window.confirm('Are you sure to delete this record?')){ this.deleteHandler(item.id)};}}> <i className="material-icons">Delete</i> </Link>
这对我有用!