【发布时间】:2017-10-27 05:14:34
【问题描述】:
我有 TouchableOpacity 的事件,我不想执行两次。
我试图将它的onPress 事件bool 置于状态,但这不起作用,因为设置状态是异步的,我可以快速按下按钮多次。
我也尝试设置计时器,但这对我也不起作用。
有没有其他方法可以防止多次按下按钮(一些其他类似的组件等)?
【问题讨论】:
标签: reactjs react-native touchableopacity
我有 TouchableOpacity 的事件,我不想执行两次。
我试图将它的onPress 事件bool 置于状态,但这不起作用,因为设置状态是异步的,我可以快速按下按钮多次。
我也尝试设置计时器,但这对我也不起作用。
有没有其他方法可以防止多次按下按钮(一些其他类似的组件等)?
【问题讨论】:
标签: reactjs react-native touchableopacity
您不需要setState 来存储不反映为 UI 更改的值。
您可以在点击 TouchableOpacity 时在 React 类中直接使用 this.flag 而不是 this.state.flag。因此,您可以设置this.flag,而不是涉及渲染周期的异步操作。它只是你的组件持有的标志。
请看下面的例子:
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
}
【讨论】: