onSwipe is trigger on swipe, it receives the swipe direction from last swipe, so background color change lags the current swipe.
npm i -S react-native-swipe-gestures
import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import GestureRecognizer, { swipeDirections } from 'react-native-swipe-gestures';
class SomeComponent extends Component {
constructor(props) {
super(props);
this.state = {
myText: 'I\'m ready to get swiped!',
gestureName: 'none',
backgroundColor: '#fff',
direction: null,
};
}
onSwipeUp(gestureState) {
this.setState({ myText: 'You swiped up!', direction: swipeDirections.SWIPE_UP });
}
onSwipeDown(gestureState) {
this.setState({ myText: 'You swiped down!', direction: swipeDirections.SWIPE_DOWN });
}
onSwipeLeft(gestureState) {
this.setState({ myText: 'You swiped left!', direction: swipeDirections.SWIPE_LEFT });
}
onSwipeRight(gestureState) {
this.setState({ myText: 'You swiped right!', direction: swipeDirections.SWIPE_RIGHT });
}
onSwipe(gestureName, gestureState) {
const { SWIPE_UP, SWIPE_DOWN, SWIPE_LEFT, SWIPE_RIGHT } = swipeDirections;
this.setState({ gestureName: gestureName });
switch (gestureName) {
case SWIPE_UP:
this.setState({ backgroundColor: 'red' });
break;
case SWIPE_DOWN:
this.setState({ backgroundColor: 'green' });
break;
case SWIPE_LEFT:
this.setState({ backgroundColor: 'blue' });
break;
case SWIPE_RIGHT:
this.setState({ backgroundColor: 'yellow' });
break;
}
}
render() {
const config = {
velocityThreshold: 0.3,
directionalOffsetThreshold: 80
};
return (
<View style={{ marginTop: 25, flex: 1 }}>
<GestureRecognizer
onSwipe={() => this.onSwipe(this.state.direction)}
onSwipeUp={() => this.onSwipeUp()}
onSwipeDown={() => this.onSwipeDown()}
onSwipeLeft={() => this.onSwipeLeft()}
onSwipeRight={() => this.onSwipeRight()}
config={config}
style={{
flex: 1,
backgroundColor: this.state.backgroundColor,
}}
>
<Text style={styles.font}>{this.state.myText}{"\n"}</Text>
<Text style={styles.font}>onSwipe callback received gesture: {this.state.gestureName}</Text>
</GestureRecognizer>
</View>
);
}
}
const styles = StyleSheet.create({
font: {
fontSize: 30
}
})
export default SomeComponent;
reference:
https://www.npmjs.com/package/react-native-swipe-gestures
No comments:
Post a Comment