【发布时间】:2018-05-24 14:30:06
【问题描述】:
我得到了一个将 PanResponder 与 React Native API 的 Animated 结合使用的组件。我的组件代码:
import React, { Component } from 'react';
import { Animated, PanResponder } from 'react-native';
import { SVG } from '../';
import { Icon, LockContainer, StatusCircle } from './styled';
class VehicleLock extends Component {
state = {
pan: new Animated.ValueXY({ x: 9, y: 16 }),
};
componentWillMount() {
this.animatedValueY = 0;
this.minYValue = 16;
this.maxYValue = 175;
this.state.pan.y.addListener((value) => {
this.animatedValueY = value.value;
});
this.panResponder = PanResponder.create({
onStartShouldSetPanResponderCapture: () => true,
onMoveShouldSetPanResponderCapture: () => true,
onPanResponderGrant: (evt, gestureState) => {
this.state.pan.setOffset({ x: 0, y: 0 });
// this.state.pan.setOffset(this.state.pan.__getValue());
this.state.pan.setValue({ x: 9, y: this.minYValue });
},
onPanResponderMove: (evt, gestureState) => {
// deltaY: amount of pixels moved vertically since the beginning of the gesture
let newY = gestureState.dy;
if (newY < this.minYValue) {
newY = this.minYValue;
} else if (newY > this.maxYValue) {
newY = this.maxYValue;
}
Animated.event([null, {
dy: this.state.pan.y,
}])(evt, {
dy: newY,
});
},
onPanResponderRelease: (evt, gestureState) => {
let newY = this.minYValue;
const releaseY = gestureState.dy;
if (releaseY > 83) {
newY = this.maxYValue;
}
Animated.spring(this.state.pan, {
toValue: {
x: 9,
y: newY,
},
}).start();
},
});
}
componentWillUnmount() {
this.state.pan.x.removeAllListeners();
this.state.pan.y.removeAllListeners();
}
render() {
const customStyles = {
...this.state.pan.getLayout(),
position: 'absolute',
zIndex: 10,
transform: [
{
rotate: this.state.pan.y.interpolate({
inputRange: [this.minYValue, this.maxYValue],
outputRange: ['0deg', '180deg'],
}),
},
],
};
return (
<LockContainer>
<SVG icon="lock_open" width={16} height={21} />
<Animated.View
{...this.panResponder.panHandlers}
style={customStyles}
>
<StatusCircle>
<Icon>
<SVG icon="arrow_down" width={23} height={23} />
</Icon>
</StatusCircle>
</Animated.View>
<SVG icon="lock_closed" width={16} height={21} />
</LockContainer>
);
}
}
export default VehicleLock;
正如您在我的代码中看到的那样,我使用边界为 Y 值设置动画。它必须保持在某些值之间的框中。一旦用户释放拖动并且它超过最大 Y 值的一半,它就会动画到最大值。
这没有任何问题,但在第二次交互时,我想反转操作。因此,它必须上升,而不是下降。不幸的是,在发布时 Y 值会重置。
正如您在我的代码中的注释中看到的那样,我知道移动是基于增量的,因此自交互开始以来移动的 Y 值。这在这个很棒的评论 PanResponder snaps Animated.View back to original position on second drag 中有解释。
在第二个输入时,元素会重新回到顶部。这是预期的行为。正如@jevakallio 在他的评论中所说,您可以在onPanResponderGrant 中重置偏移量中的值。当我这样做(已注释掉)时,元素会重置值,但在第二次交互时,它会在容器的 outside 设置动画。所以在那种情况下0 是maxYValue 并且它在容器外将175 动画到底部。
如何使反向动画从外部回到顶部?我似乎不明白这一点。提前致谢!
【问题讨论】:
标签: javascript reactjs animation react-native draggable