问题
I have TouchableOpacity
with event that I don't want to execute twice.
I tried to put in it's onPress
event bool
in state but this doesn't work as setting state is async and I can press button multiple times fast.
I also tried to set timer but this also doesn't work for me.
Is there any other way to prevent multiple press on button (some other similar component etc.)?
回答1:
You do not need to setState
to store values which do not reflect as UI changes.
You could directly have a this.flag
instead of this.state.flag
inside your React Class which you set on TouchableOpacity click. So, you can set this.flag
without it being asynchronous operation involving a render cycle. It'll just be a flag which your component holds.
See example below:
class SomeComponent extends React.Component{
constructor() {
super();
this.state = { ... }; // this does not need to store our flag
this.touchableInactive = false; // this is not state variable. hence sync
}
onButtonClick () {
if (!this.touchableInactive) {
this.touchableInactive = true;
// do stuff
}
}
// similarly reset this.touchableInactive to false somewhere else
}
来源:https://stackoverflow.com/questions/46963837/how-to-make-touchableopacity-button-to-prevent-multiple-clicks