我发现的官方文档和所有教程都将PanResponder用作React Classs的一部分,但是有没有办法将其与功能组件和挂钩一起使用? 我尝试按照以下步骤进行操作,但似乎不起作用:-
const App = props => {
const position = useRef(new Animated.ValueXY()).current;
const panResponder = useRef(
PanResponder.create({
onStartShouldSetPanResponder: (evt, gestureState) => true,
onPanResponderMove: (evt, gestureState) => {
position.setValue({x: gestureState.dx, y: gestureState.dy});
},
onPanResponderRelease: (evt, gestureState) => {},
}),
).current;
...
<Animated.View
{...panResponder.panHandlers}
style={[
{transform: position.getTranslateTransform()},
styles.appStyles,
]}>
...
</Animated.View>
答案 0 :(得分:1)
在此处找到解决方案:https://github.com/facebook/react-native/issues/25360#issuecomment-505241400
useMemo避免在每次重新渲染时重新创建PanResponder
然后您的代码应如下所示
const App = props => {
const position = useRef(new Animated.ValueXY()).current;
const panResponder = React.useMemo(() => PanResponder.create({
onStartShouldSetPanResponder: (evt, gestureState) => true,
onPanResponderMove: (evt, gestureState) => {
position.setValue({x: gestureState.dx, y: gestureState.dy});
},
onPanResponderRelease: (evt, gestureState) => {},
}), []);
...
<Animated.View
{...panResponder.panHandlers}
style={[
{transform: position.getTranslateTransform()},
styles.appStyles,
]}>
...
</Animated.View>