How to make TouchableOpacity button to prevent multiple clicks

旧时模样 提交于 2021-01-28 10:24:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!