我正在尝试延迟按钮单击,以便我使用的库可以快速进行 api 调用以进行验证。我目前正在 React 中使用箭头函数并尝试 setTimeout。然而,由于某种原因,这似乎触发了页面加载的调用。这是我的代码。
onClick={this.handleCardSubmit}
handleCardSubmit = setTimeout(() => {
this.setState({ showLoaderForPayment: true });
const { collectJs } = this.state;
collectJs.startPaymentRequest();
this.setState({ isPaymentRequestCalled: true });
}, 500);
最佳答案
您好,您需要更改函数声明和定义,如下
handleCardSubmit = ()=>{
setTimeout(() => {
this.setState({ showLoaderForPayment: true });
const { collectJs } = this.state;
collectJs.startPaymentRequest();
this.setState({ isPaymentRequestCalled: true });
}, 500);
}
在您的代码片段中,您只是将 settimeout 函数引用传递给 handeCardSubmit ,因此没有绑定(bind)。为了正确执行它,你必须在箭头函数中编写setTimeout函数,然后它就会像延迟500ms一样工作。
关于javascript - 如何在 react 中添加按钮点击延迟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58987789/