我在做什么:更改状态以响应用户的向上/向下滑动。环境:反应原生 0.61.5
我的组件如下。
import React, { useRef, useState } from 'react';
import { View, PanResponder } from 'react-native';
function SimpleWrapper(props) {
const { children } = props;
const [abc, setabc] = useState(0);
console.log('SimpleWrapper', abc);
const panResponder = useRef(
PanResponder.create({
onStartShouldSetPanResponder: (evt, gestureState) => handleShouldSetPanResponder(evt, gestureState),
// onStartShouldSetPanResponderCapture: (evt, gestureState) => handleShouldSetPanResponder(evt, gestureState),
onMoveShouldSetPanResponder: (evt, gestureState) => handleShouldSetPanResponder(evt, gestureState),
// onMoveShouldSetPanResponderCapture: (evt, gestureState) => handleShouldSetPanResponder(evt, gestureState),
// onPanResponderGrant: (evt, gestureState) => console.log('onPanResponderGrant', gestureState),
onPanResponderMove: (evt, gestureState) => handleonPanResponderMove(evt, gestureState),
onPanResponderTerminationRequest: () => {}
// onPanResponderRelease: (evt, gestureState) => handlePanResponderRelease(evt, gestureState)
})
).current;
const handleShouldSetPanResponder = (evt, gestureState) => {
const { dy } = gestureState;
const isvalid = evt.nativeEvent.touches.length === 1 && Math.abs(dy) > gestureConfig.gestureIsClickThreshold;
return isvalid;
};
const handleonPanResponderMove = (evt, gestureState) => {
const { dy, vy } = gestureState;
console.log('in handleonPanResponderMove:', abc, gestureState);
if (dy < 0) {
setabc(abc + 1);
} else if (dy > 0) {
setabc(abc - 1);
}
// }
};
return (
<View {...panResponder.panHandlers} style={}>
{children}
</View>
);
}
export default SimpleWrapper;
基本上我想增加/减少onMoveShouldSetPanResponder中的状态参数,
现在,在 onMoveShouldSetPanResponder 第一次触发时,'abc' 已成功递增/递减。组件中最顶层的控制台也显示了新值。
但是,在所有连续触发之后,onMoveShouldSetPanResponder 函数内的控制台始终将 abc 打印为0(即初始值)。它永远不会改变。
是不是我们无法访问 onMoveShouldSetPanResponder 内部的更新状态?我错过了什么还是有其他方法可以做到这一点?