gpt4 book ai didi

reactjs - 如何在功能组件中使用PanResponder?

转载 作者:行者123 更新时间:2023-12-03 13:36:52 24 4
gpt4 key购买 nike

我发现的官方文档和所有教程都使用 PanResponder 作为 React 类的一部分,但是有没有办法我们可以将它与功能组件和钩子(Hook)一起使用?我尝试按如下方式执行此操作,但似乎不起作用:-

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>

最佳答案

在这里找到解决方案: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>

关于reactjs - 如何在功能组件中使用PanResponder?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58939572/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com