I try to compute a carousel with bounces on side. I try to do it on my self since bounces props are not supported on Android.
My component works perfectly, but for some reason I am not able to reproduce bounces when the user was previously scrolling and comes to the end of the scrollview (at this moment, it should bounce).
The only way to make it bounces currently is to be already at the end of the scrollview before touching.
For some reason, onPanResponderMove is not called when user is scrolling the scrollview.
My code :
import React from 'react';
import { StyleSheet, ScrollView, Animated, PanResponder, View } from 'react-native';
class Carousel extends React.Component {
constructor(props){
super(props);
this._props = props;
this._scrolledtoLeft = true;
this._scrolledtoRight = false;
this._gestureState = null;
this._shift = 0;
this._pan = new Animated.ValueXY();
this._panResponder = PanResponder.create({
onMoveShouldSetPanResponder: () => true,
onPanResponderMove: (e, gestureState) => {
this._gestureState = gestureState;
if(gestureState.dx >= 0 && this._scrolledtoLeft){
var x = gestureState.dx - this._shift;
if(x < 0){
x = 0;
}
x /= 2;
if(x > 150){
x = 150;
}
this._pan.setValue({x: x, y: 0});
Animated.event([
null,
{}
],
{useNativeDriver: false})(e, gestureState);
}
else if(gestureState.dx <= 0 && this._scrolledtoRight){
var x = gestureState.dx - this._shift;
console.log(x);
if(x > 0){
x = 0;
}
x /= 2;
if(x < -150){
x = -150;
}
console.log(x);
this._pan.setValue({x: x, y: 0});
Animated.event([
null,
{}
],
{useNativeDriver: false})(e, gestureState);
}
},
onPanResponderRelease: () => {
Animated.timing(this._pan, { toValue: {x: 0, y: 0 }, duration: 400, useNativeDriver: false }).start(() => {
});
}
});
}
render() {
return (
<Animated.ScrollView {...this._props} horizontal={true} scrollEventThrottle={1} onScroll={(event) => { this.onScroll(event); } } showsHorizontalScrollIndicator={true} bounces={false} style={[{ transform: [{ translateX: this._pan.x }]}, styles.scrollView, this._props.style]} {...this._panResponder.panHandlers}>
<View style={{ width: this._props.paddingSides }}></View>
{this._props.children}
<View style={{ width: this._props.paddingSides }}></View>
</Animated.ScrollView>
)
}
onScroll(event){
console.log(event.nativeEvent);
if(event.nativeEvent.contentOffset.x == 0){
if(!this._scrolledtoLeft){
this._shift = this._gestureState.dx;
}
this._scrolledtoLeft = true;
}
else{
this._scrolledtoLeft = false;
}
if(event.nativeEvent.layoutMeasurement.width + event.nativeEvent.contentOffset.x == event.nativeEvent.contentSize.width){
if(!this._scrolledtoRight){
this._shift = this._gestureState.dx;
}
this._scrolledtoRight = true;
}
else{
this._scrolledtoRight = false;
}
}
}
const styles = StyleSheet.create({
scrollView: {
}
});
export default Carousel;
question from:
https://stackoverflow.com/questions/65648855/panresponder-in-scrollview 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…