在 React 中确认窗口



我有以下代码:

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和调用binded函数的正确synatx。

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>

我定义了一个函数来调用删除端点,因为-

deleteHandler(props){
axios.delete(`http://localhost:3000/api/v1/product?id=${props}`)
.then(res => {
console.log('Deleted Successfully.');
})
}

这对我有用!

最新更新