React Native: Constraining Animated.Value

落爺英雄遲暮 提交于 2020-02-03 04:10:23

问题


I'm making a React-Native app and the scenario is this: I want the user to be able to pan a view, but not wholly the way he wants. I'd like to constraint how much the view can move when being dragged by the user.

I've read through the documentation of both the PanResponder and Animated API (multiple times), but can't find anything that does this, neither can I find anyone else that implemented something alike.

Constraining in the panresponder's event?

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

Constraining while applying the transforms?

style = {
    transform: {
        transformX: ...,//Use interpolate to constrain the values somehow?
        transformY: ...
    }
}

回答1:


Or you could use the extrapolate, extrapolateRight or extrapolateLeft properties:

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

seems to me to do the same as @mieszko4, of which I don't know why the Infinity hack was needed.

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




回答2:


The solution I came up with: Since Animated.event() returns a function, you can just pass your processed gestureState, with constrained values, into that function.
It'd look something like this:

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});
},

Whether it's it should be done is debatable though.




回答3:


The solution provided by @stinodes will degrade performance. Why not using interpolate in the following way:

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



回答4:


const constrainedX = this.state.pan.x.interpolate({
      inputRange: [leftLimit, 0, rightLimit],
      outputRange: [leftLimit, 0, rightLimit],
      extrapolate: 'clamp'
})

extapolate: 'clamp' will keep it in bounds.



来源:https://stackoverflow.com/questions/36746608/react-native-constraining-animated-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!