【发布时间】:2018-09-26 21:18:17
【问题描述】:
我正在使用 panResponder,我正在创建一个跟随用户手指的简单视图。我查了一下,发现这个例子有效并且我正在使用它,但我无法理解它。
constructor(props){
this.state = {
pan: new Animated.ValueXY()
}
this._val = { x: 0, y: 0 };
this.state.pan.addListener(value => (this._val = value));
// Initialize PanResponder with move handling
this.panResponder = PanResponder.create({
onStartShouldSetPanResponder: (e, gesture) => true,
onPanResponderMove: Animated.event([
null,
{ dx: this.state.pan.x, dy: this.state.pan.y },
]),
onPanResponderGrant: (e, gesture) => {
// can't understand this part
this.state.pan.setOffset({
x: this._val.x,
y: this._val.y,
});
this.state.pan.setValue({ x: 0, y: 0 });
}
}
所以,据我所知,当用户移动手指时,会使用 Animated.event 调用 onPanResponderMove,其中将 this.state.pan.x 和 this.state.pan.y 设置为 delta x 和 y手势,这意味着如果用户将手指移动到底部 50 度和向右移动 50 度,this.state.pan 将类似于 {x:50,y:50}。
现在我为什么要为 onPanResponderGrant 设置偏移量? 从我看到的偏移量将是 50(之前的值 + 50,当 ANimated.event 在 onPanResponderMove 上设置值时,从 this._val.x 中获取的 dx)所以视图应该移动 100? 然后我们清除 this.state.pan 的值?
有人可以更好地解释一下发生了什么吗?也许有一些简单的数字或一步一步的例子? 希望你能帮助我,整整一天都在试图弄清楚。 谢谢!
【问题讨论】:
标签: reactjs react-native animation gesture react-animated