React Native onPanResponderMove似乎很少被调用

时间:2017-09-02 13:59:48

标签: javascript android ios typescript react-native

我正在尝试在React Native中实现自定义垂直滑块。为此,我使用PanResponder。由于滑块是垂直的,我只更改y值。要停止滑块边框上的对象,我在调用Animated.event之前检查它是否已到达。

我的滑块工作正常,直到我快速滑动对象。然后onPanResponderMove回调似乎被调用太少,并且对象停在轨道之外,而不是边界。

componentWillMount() {
    this.panResponder = PanResponder.create({
        onStartShouldSetPanResponder: (evt, gestureState) => true,
        onStartShouldSetPanResponderCapture: (evt, gestureState) => true,
        onMoveShouldSetPanResponder: (evt, gestureState) => true,
        onMoveShouldSetPanResponderCapture: (evt, gestureState) => true,
        onPanResponderGrant: this._handleOnPanResponderGrant.bind(this),
        onPanResponderMove: this._handleOnPanResponderMove.bind(this),
        onPanResponderRelease: this._handleOnPanResponderRelease.bind(this)
    })
}

_handleOnPanResponderGrant() {
    this.state.pan.setOffset({ x: this.state.pan.x._value, y: this.state.pan.y._value })
    this.state.pan.setValue({ x: 0, y: 0 })
}

_handleOnPanResponderMove(e, gestureState) {
    // some calculations - seems to be correct since everything is working fine until I swipe very fast
    if (reachedBorders(...)) { // this takes into account also the direction so it won't get stuck on the border
        return true
    }
    return Animated.event([null, { dy: this.state.pan.y }])(e, gestureState)
}

_handleOnPanResponderRelease() {
    this.state.pan.flattenOffset()
}

我做错了什么?我的方法是否正确(如果在滑块之外,则跳过Animated.event)?

更新

问题可能是您无法在this GitHub issue中描述的手势中立即停止PanResponder移动。

1 个答案:

答案 0 :(得分:0)

您可以让PanResponder值的使用者使用pan.y值,而不是试图阻止pan更新interpolated值。例如,如果边框位于10250,您可以使用以下内容:

... style={{transform: [{translateY: this.state.pan.y.interpolate({
       inputRange: [10, 250],
       outputRange: [10, 250],
       extrapolate: 'clamp'
     })}]}}

Release方法中,您还需要将值限制在边框内,但插值会阻止动画过度。