如何制作 TouchableOpacity 按钮以防止多次点击 [英] How to make TouchableOpacity button to prevent multiple clicks

查看:241
本文介绍了如何制作 TouchableOpacity 按钮以防止多次点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 TouchableOpacity 事件,我不想执行两次.

我试图将它的 onPress 事件 bool 置于 state 中,但这不起作用,因为设置状态是异步的,我可以快速按下按钮多次.

我也尝试设置计时器,但这对我也不起作用.

有没有其他方法可以防止多次按下按钮(其他一些类似的组件等)?

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.)?

推荐答案

您不需要 setState 来存储不反映为 UI 更改的值.

You do not need to setState to store values which do not reflect as UI changes.

您可以在您在 TouchableOpacity 单击时设置的 React 类中直接使用 this.flag 而不是 this.state.flag .因此,您可以设置 this.flag 而不是涉及渲染周期的异步操作.它只是您的组件持有的标志.

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.

见下面的例子:

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
}

这篇关于如何制作 TouchableOpacity 按钮以防止多次点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆