做项目的时候遇到了这个需求,react native阻止重复点击、阻止反复点击,第一想到的是给点击事件一个定时,要距离上一次点击的时间大于1秒的之后再执行
// 新建一个js文件命名为
// preventDoublePress.js
const preventDoublePress = {
lastPressTime: 1, // 上次点击时间
reponTime: 1000, // 间隔时间
onPress(callback) {
let curTime = Date.now();
if (curTime - this.lastPressTime > this.reponTime) {
this.lastPressTime = curTime;
this.reponTime = 1000; // 这里的时间和上面的匹配
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={{
/*
2. 将动画值绑定到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={{
/*
2. 将动画值绑定到style的属性
* */
opacity: this.state.fadeAnim
}}>
Simple Animated Used Animated.timing
</Animated.Text>
<Button title="touch me" onPress={() => {
preventDoublePress.reponTime = 5000 // 单独设置间隔时间
preventDoublePress.onPress(() => this.showAnim())}}
/>
</View>
)
}
}
有好的思路欢迎评论交流。