如何解决React Native:重新渲染后panGestureHandler停止工作
我的0.62.2应用程序中有一个简单的拖动动画。拖动是通过react-native-gesture-handler 1.6.1
和react-native-reanimated 1.10.1
实现的。拖动的项目是正方形网格中的图像。连续有2个网格或3个网格可显示图像。这是在方法displayImg
中渲染单个图像的代码:
const displayImg = (img_source,width,ht,index,modalWidth,modalHt,dataLen,sortFn) => {
....
const dragX = new Value(0);
const dragY = new Value(0);
const offsetX = new Value(0);
const offsetY = new Value(0);
const addX = add(offsetX,dragX);
const addY = add(offsetY,dragY);
const state = new Value(-1);
const scale = new Value(1);
const transX = cond(eq(state,State.ACTIVE),addX,set(offsetX,addX));
const transY = cond(eq(state,addY,[
cond(eq(state,State.END),call([addX,aniIndex,aniGridPR],onUp)),//<<==onUp is method called after State.END,nothign but a console output for now.
set(offsetY,addY),]);
const handleGesture = event([
{
nativeEvent: {
translationX: dragX,translationY: dragY,state,},]);
let aniStyle = {
transform:[
{ translateX : transX },{ translateY : transY },]
};
return (
<>
<PanGestureHandler
onGestureEvent={handleGesture}
onHandlerStateChange={handleGesture}
minPointers={1}
maxPointers={1}>
<Animated.View style={[aniStyle ]}>
<GridImage
img_source={img_source}
width={width}
ht={ht}
index={index}
/>
</Animated.View>
</PanGestureHandler>
这是渲染图像数组的渲染代码:
return (
<Grid style={{position:"absolute",paddingTop:0,paddingLeft:0}}>
{pics.map((item,index) => { //<<==pics is an image array
if (index%2===0) {
if (pics[index+1]) {
return (
<Row style={styles.row}>
{displayImg(picPath(item),screen_width*half,screen_width,item.height*(screen_width/item.width),len,move)}
{displayImg(picPath(pics[index+1]),index+1,pics[index+1].height*(screen_width/pics[index+1].width),move)}
</Row>
)} else {
return (
<Row style={styles.row}>
{displayImg(picPath(item),move)}
</Row>
)};
}
})}
</Grid>
);
可以拖动图像。但是,在添加新图像并导致重新渲染之后,无法拖动以前加载的图像并停止响应拖动。但是,新添加的图像仍然可以拖动。我感觉到问题可能与平移手势处理和动画的代码有关,但是无法找出问题出在哪里。有post关于类似的问题,但并不完全相同。
解决方法
解决方案是在重新渲染后使用useValue
保留图像组件的状态。由于useValue
是一个钩子,因此不能在条件下使用。方法displayImg
转换为组件DisplayImg
,动画变量的声明移至组件DisplayImg
的顶部。
import Animated,{useValue} from "react-native-reanimated";
function DisplayImg() {
const aniIndex= new Value(index);
const dragX = useValue(0);
const dragY = useValue(0);
const offsetX = new Value(0);
const offsetY = new Value(0);
var transX = useValue(0);
var transY = useValue(0);
const state = new Value(-1);
const scale = new Value(1);
......
}
根据经验,所有动画值都应useValue
以根据react-native-gesture-handler
team保留状态。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。