页面上有几个按钮,如果我单击按钮,就会进行 ajax 调用。我想禁用该按钮,这样用户就不会再次单击它,并且不会进行另一个 ajax 调用。
我尝试了下面的代码,但按钮没有禁用。 我也想显示 react 成功的通知 - 我尝试了 toast ,但它也不起作用。
还有其他方法可以在 React 中显示气球弹出窗口吗?
请提出建议,
onClickRun(params) {
const url = `/api/${params}/run`;
const id = "run"+params;
return $.ajax({
type: 'POST',
url,
processData: false,
contentType: 'application/json',
beforeSend :() =>{
// $("#run"+params).classList.add("cursorDisabled");
// $("#run"+params).attr('disabled',true);
document.getElementById(id).disabled = true;
document.getElementById(id).classList.add('cursorDisabled');
},
success: (response) => {
if(!response.error) {
// toast({
// message: 'Pipeline ran successfully.',
// flavor: 'success',
// options: { timeOut: 5000 }
// });
//$("#"+params).classList.remove("cursorDisabled");
//$("#run"+params).attr('disabled',false);
document.getElementById(id).disabled = false;
document.getElementById(id).classList.remove('cursorDisabled');
location.reload(true);
}
},
error: (error) => {
console.log("error");
}
});
}
CSS 代码:
.cursorDisabled{
cursor: not-allowed;
color: gray;
}
按钮:
<button id= {"run"+col.name} type="button" onClick={() => this.onClickRun(col.name)} <i className="icon-play-filled"></i>
</button>
最佳答案
嗯,有一个简单的修复方法,使用 React 的 setState 方法。 您需要进行以下更改
<button id= {"run"+col.name} type="button" onClick={() => this.onClickRun(col.name)} <i className="icon-play-filled"></i>
将其替换为
<button id= {"run"+col.name} className={this.state.clickedButton === col.name ? 'cursorDisabled' : ''} disabled={this.state.clickedButton === col.name} type="button" onClick={() => this.onClickRun(col.name)} <i className="icon-play-filled"></i>
;
-
2.
onClickRun(params) {
const url = `/api/${params}/run`;
const id = "run"+params;
return $.ajax({
type: 'POST',
url,
processData: false,
contentType: 'application/json',
beforeSend :() =>{
// $("#run"+params).classList.add("cursorDisabled");
// $("#run"+params).attr('disabled',true);
document.getElementById(id).disabled = true;
document.getElementById(id).classList.add('cursorDisabled');
this.setState({
clickedButton: params
})
},
success: (response) => {
this.setState({
clickedButton: ''
})
if(!response.error) {
// toast({
// message: 'Pipeline ran successfully.',
// flavor: 'success',
// options: { timeOut: 5000 }
// });
//$("#"+params).classList.remove("cursorDisabled");
//$("#run"+params).attr('disabled',false);
document.getElementById(id).disabled = false;
document.getElementById(id).classList.remove('cursorDisabled');
location.reload(true);
}
},
error: (error) => {
console.log("error");
this.setState({
clickedButton: ''
})
}
});
}
- 使用添加新状态
state = {
clickedButton: ''
}
一切准备就绪。
关于javascript - React - 在 ajax 调用期间按钮未禁用,toast 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54835496/