React Native:约束Animated.Value

sti*_*des 9 javascript animation react-native

我正在创建一个React-Native应用程序,方案是这样的:我希望用户能够平移视图,但不是完全按照他想要的方式.我想限制视图在被用户拖动时可以移动多少.

我已经阅读了API PanResponderAnimatedAPI 的文档(多次),但找不到任何可以做到这一点的东西,我也找不到任何其他类似的东西.

限制在响应者的事件中?

onPanResponderMove: Animated.event([null,{
    dx: this.state.pan.x,  //Some function here to constrain the value?
    dy: this.state.pan.y
}]),
Run Code Online (Sandbox Code Playgroud)

应用变换时的约束?

style = {
    transform: {
        transformX: ...,//Use interpolate to constrain the values somehow?
        transformY: ...
    }
}
Run Code Online (Sandbox Code Playgroud)

deb*_*0ch 10

使用extrapolate,extrapolateRightextrapolateLeft属性:

const maxX = 200;
const constrainedX = this.state.pan.x.interpolate({
  inputRange: [0, maxX],
  outputRange: [0, maxX],
  extrapolateRight: 'clamp'
})
Run Code Online (Sandbox Code Playgroud)

https://facebook.github.io/react-native/docs/animations.html#interpolation


sti*_*des 7

我想出的解决方案:由于Animated.event()返回一个函数,您可以将处理过的带有约束值的手势状态传递给该函数。
它看起来像这样:

onPanResponderMove: (evt, gestureState) => {
    let newdx = gestureState.dx, //DO SOMETHING WITH YOUR VALUES
        newdy = gestureState.dy;
    Animated.event([null,{
        dx: this.state.pan.x,
        dy: this.state.pan.y
    }])(evt, {dx: newdx, dy: newdy});
},
Run Code Online (Sandbox Code Playgroud)

是否应该这样做是有争议的。


小智 6

@stinodes 提供的解决方案会降低性能。为什么不interpolate按以下方式使用:

const maxX = 200;
const constrainedX = this.state.pan.x.interpolate({
  inputRange: [0, maxX, Infinity],
  outputRange: [0, maxX, maxX]
})
Run Code Online (Sandbox Code Playgroud)