做项目的时候遇到了这个需求,react native阻止重复点击、阻止反复点击,第一想到的是给点击事件一个定时,要距离上一次点击的时间大于2秒的之后再执行
// 新建一个js文件命名为
// preventDoublePress.js
const preventDoublePress = {
lastPressTime: 1, // 上次点击时间
onPress(callback,wait=500) {
let curTime = Date.now();
if (curTime - this.lastPressTime > wait) {
this.lastPressTime = curTime;
callback();
}
},
};
module.exports = preventDoublePress;
在项目中使用这个方法
// 这个是我的文件引入路径
import preventDoublePress from '../../global/preventDoublePress';
在点击函数onpress中使用preventDoublePress方法
import React, { Component } from 'react';
import {
View,
Button,
Animated,
ToastAndroid,
} from 'react-native';
import styles from './Style'
import preventDoublePress from '../../global/preventDoublePress';
export default class MeScreen extends Component {
constructor(props) {
super(props);
this.state = {
fadeAnim: new Animated.Value(0)
}
}
showAnim = () => {
/*
3. 处理动画值,并启动动画
* */
this.state.toValue = this.state.toValue == 1 ? 0 : 1
Animated.timing(
this.state.fadeAnim,
{
duration: 1000,
toValue: this.state.toValue,
useNativeDriver: true
}
).start();
ToastAndroid.show('显示动画效果', ToastAndroid.SHORT)
}
// 页面
render() {
return (
<View style={styles.container}>
<Animated.Text style={{
opacity: this.state.fadeAnim
}}>
Simple Animated Used Animated.timing
</Animated.Text>
<Button title="touch me" onPress={() => preventDoublePress.onPress(() => this.showAnim())} />
</View>
)
}
}
在点击的时候还可以设置间隔时间进行单独控制
import React, { Component } from 'react';
import {
View,
Button,
Animated,
ToastAndroid,
} from 'react-native';
import styles from './Style'
import preventDoublePress from '../../global/preventDoublePress';
export default class MeScreen extends Component {
constructor(props) {
super(props);
this.state = {
fadeAnim: new Animated.Value(0)
}
}
showAnim = () => {
/*
3. 处理动画值,并启动动画
* */
this.state.toValue = this.state.toValue == 1 ? 0 : 1
Animated.timing(
this.state.fadeAnim,
{
duration: 1000,
toValue: this.state.toValue,
useNativeDriver: true
}
).start();
ToastAndroid.show('显示动画效果', ToastAndroid.SHORT)
}
// 页面
render() {
return (
<View style={styles.container}>
<Animated.Text style={{
opacity: this.state.fadeAnim
}}>
Simple Animated Used Animated.timing
</Animated.Text>
<Button title="touch me" onPress={() => {
// 第二个参数是间隔时长
preventDoublePress.onPress(() => this.showAnim(),2000)
}} />
</View>
)
}
}
有好的思路欢迎评论交流。