做項目的時候遇到了這個需求,react native阻止重復(fù)點擊、阻止反復(fù)點擊,第一想到的是給點擊事件一個定時,要距離上一次點擊的時間大于2秒的之后再執(zhí)行
// 新建一個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';
在點擊函數(shù)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>
)
}
}
在點擊的時候還可以設(shè)置間隔時間進行單獨控制
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={() => {
// 第二個參數(shù)是間隔時長
preventDoublePress.onPress(() => this.showAnim(),2000)
}} />
</View>
)
}
}
有好的思路歡迎評論交流。