React Native函数组件实现Tinder卡片时interpolate报is not a function错误
问题解决:Animated的Interpolate函数调用返回is not a function错误
错误根因
- 手势回调中错误覆盖了Animated值类型:你初始化的
pan是Animated.ValueXY实例,但是在onPanResponderMove回调中,直接通过setPan将其替换为了普通的{x: 数字, y: 数字}对象,Animated实例的内置方法全部丢失,自然无法调用interpolate。 - 对Animated值执行了普通数值运算:你调用了
Math.round(pan.x),该操作会直接返回普通数字类型,只有Animated.Value实例才具备interpolate方法,普通数字调用该方法自然会报错。
修复后代码
import React, { useRef } from 'react' import { Text, View, Animated, Image, StyleSheet, PanResponder } from 'react-native' function Card(props){ const { screen_height, screen_width, image, Data, currentIndex, Index } = props; // 用useRef存储Animated值,不需要触发重渲染,也不会被错误覆盖实例类型 const pan = useRef(new Animated.ValueXY()).current; // PanResponder直接定义即可,不需要存入useState const panResponder = PanResponder.create({ onStartShouldSetPanResponder: (evt, gestureState) => true, onPanResponderMove: Animated.event( [null, { dx: pan.x, dy: pan.y }], { useNativeDriver: false } ), onPanResponderRelease: (evt, gestureState) => { // 后续松手逻辑在这里补充 } }); // interpolate直接调用pan.x(Animated.Value实例)的方法即可,不要提前做数值转换 console.log(pan.x.interpolate({ inputRange: [0, 1], outputRange: [150, 0]})); if (Index < currentIndex) { return null } else if(Index == currentIndex){ return( <Animated.View style={[{ transform:[{ translateX: pan.x }, { translateY: pan.y }] },{ height:screen_height - 120, width:screen_width, padding:10, position:'absolute' }]} {...panResponder.panHandlers}> <Image style={[{ flex:1, height:null, width:null, resizeMode:"cover", borderRadius:20, }]} source={image.uri}/> </Animated.View>) } else { return( <Animated.View style={[{ height:screen_height - 120, width:screen_width, padding:10, position:'absolute' }]}> <Image style={[{ flex:1, height:null, width:null, resizeMode:"cover", borderRadius:20, }]} source={image.uri}/> </Animated.View>) } } export default Card;
内容的提问来源于stack exchange,提问作者CharlieWhite
相关产品推荐
相关产品推荐

