ReactJs:防止多次按下按钮 [英] ReactJs: Prevent multiple times button press
问题描述
在我的React组件中,我有一个按钮,用于在单击时通过AJAX发送一些数据。我只需要第一次发生,即在第一次使用后禁用按钮。
In my React component I have a button meant to send some data over AJAX when clicked. I need to happen only the first time, i.e. to disable the button after it's first use.
我是如何尝试这样做的:
How I'm trying to do this:
var UploadArea = React.createClass({
getInitialState() {
return {
showUploadButton: true
};
},
disableUploadButton(callback) {
this.setState({ showUploadButton: false }, callback);
},
// This was simpler before I started trying everything I could think of
onClickUploadFile() {
if (!this.state.showUploadButton) {
return;
}
this.disableUploadButton(function() {
$.ajax({
[...]
});
});
},
render() {
var uploadButton;
if (this.state.showUploadButton) {
uploadButton = (
<button onClick={this.onClickUploadFile}>Send</button>
);
}
return (
<div>
{uploadButton}
</div>
);
}
});
我认为发生的是状态变量 showUploadButton
没有立即更新,React docs说的是预期的。
What I think happens is the state variable showUploadButton
not being updated right away, which the React docs says is expected.
我怎么能强制按钮被禁用或在点击它的瞬间全部消失?
How could I enforce the button to get disabled or go away all-together the instant it's being clicked?
推荐答案
您可以做的是点击后将按钮禁用并将其保留在页面中(不是可点击的元素)。
What you could do is make the button disabled after is clicked and leave it in the page (not clickable element).
要实现这一点,你必须在按钮元素中添加一个参考
To achieve this you have to add a ref to the button element
<button ref="btn" onClick={this.onClickUploadFile}>Send</button>
然后在onClickUploadFile函数上禁用按钮
and then on the onClickUploadFile function disable the button
this.refs.btn.setAttribute("disabled", "disabled");
然后,您可以相应地设置禁用按钮的样式,以便用
You can then style the disabled button accordingly to give some feedback to the user with
.btn:disabled{ /* styles go here */}
如果需要,请务必使用
this.refs.btn.removeAttribute("disabled");
更新:在React中处理refs的首选方法是使用函数而不是字符串。
Update: the preferred way of handling refs in React is with a function and not a string.
<button
ref={btn => { this.btn = btn; }}
onClick={this.onClickUploadFile}
>Send</button>
this.btn.setAttribute("disabled", "disabled");
this.btn.removeAttribute("disabled");
这是使用您提供的代码的一个小例子
https://jsfiddle.net/69z2wepo/30824/
here is a small example using the code you provided https://jsfiddle.net/69z2wepo/30824/
这篇关于ReactJs:防止多次按下按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!