ReactNative PanResponder 限制 X 位置 [英] ReactNative PanResponder limit X position
问题描述
我正在构建一个音乐播放器,我专注于进度条.我能够对滑动手势做出反应,但我无法限制该手势的作用范围.
I'm building a Music Player and I'm focusing on the progress bar. I was able to react to swipe gestures, but I cant limit how far that gesture goes.
这是我迄今为止所做的.我已将所有内容降至最低:
This is what I've done so far. I've reduced everything to the minumal:
constructor(props) {
super(props);
this.state = {
pan: new Animated.ValueXY()
};
}
componentWillMount() {
this._panResponder = PanResponder.create({
onMoveShouldSetResponderCapture: () => true,
onMoveShouldSetPanResponderCapture: () => true,
onPanResponderGrant: (e, gestureState) => {
// Set the initial value to the current state
let x = (this.state.pan.x._value < 0) ? 0 : this.state.pan.x._value;
this.state.pan.setOffset({ x, y: 0 });
this.state.pan.setValue({ x: 0, y: 0 });
},
onPanResponderMove: Animated.event([
null, { dx: this.state.pan.x, dy: 0 },
]),
onPanResponderRelease: (e, { vx, vy }) => {
this.state.pan.flattenOffset();
}
});
}
render() {
let { pan } = this.state;
// Calculate the x and y transform from the pan value
let [translateX, translateY] = [pan.x, pan.y];
// Calculate the transform property and set it as a value for our style which we add below to the Animated.View component
let imageStyle = { transform: [{ translateX }, { translateY }] };
return (
<View style={styles.container}>
<Animated.View style={{imageStyle}} {...this._panResponder.panHandlers} />
</View>
);
}
这里有一张图片显示了问题所在.
Here there is an image showing what the problem is.
所以我们的想法是一旦达到限制(向左和向右)就停止移动.我尝试检查 _value <0
,但它不起作用,因为它似乎是一个偏移量,而不是一个位置.
So the idea is to stop keeping moving once the limit (left as well as right) is reached. I tried checking if _value < 0
, but it didn't work since It seems to be an offset, not a position.
任何帮助将不胜感激.
推荐答案
与其让你的动画死在你的边界,你可以插入你的Animated.Value 与 y=x,但将其固定到您的宽度.
Instead of letting your animation die at your borders, you could interpolate your Animated.Value with y=x, but with clamping it to your width.
return (
<View style={styles.container}>
<Animated.View
style={{
transform: [{
translateX: this.state.pan.x.interpolate({
inputRange: [0, trackWidth ],
outputRange: [0, trackWidth ],
extrapolate: 'clamp'
})
}],
}}
{...this._panResponder.panHandlers}
/>
</View>
);
这里有一个更深入的例子:https://github.com/olapiv/expo-audio-player/blob/master/src/AudioSlider.js
Here's a more in-depth example: https://github.com/olapiv/expo-audio-player/blob/master/src/AudioSlider.js
这篇关于ReactNative PanResponder 限制 X 位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!