React Native使用GestureFlipView的翻牌在3×3网格仅最后一张可正常翻转
问题原因及修复方案
核心问题
- 你在函数式
Cards组件中使用this.flipView存储组件ref,this在函数式组件执行时指向全局对象,所有卡片实例渲染时都会覆盖同一个ref变量,最终只有最后一张卡片的ref被正确保留,因此只有最后一张卡片可以正常触发翻转 - FlatList渲染时传参错误,你的DATA数组中存储卡片数值的字段是
title,但你传递给Cards组件的是item.value,会导致所有卡片数值显示为undefined - GestureFlipView当前设置的宽高为300*500,远大于3列布局下每个卡片的容器尺寸,会导致布局溢出
修复后的代码
Cards组件
import {View, Text, SafeAreaView, TouchableOpacity} from 'react-native'; import GestureFlipView from 'react-native-gesture-flip-card'; import { useState, useRef } from 'react'; const Cards = (props) => { // 用useRef存储当前卡片实例的翻转组件ref,不会和其他卡片冲突 const flipRef = useRef(null); const [flipType, setFlip] = useState('left'); const renderFront = () => { return( <TouchableOpacity onPress = {() => { flipRef.current.flipRight() setFlip('right'); console.log("Pressed" + `${props.val}`) }} > <View style = {{backgroundColor:'red', width: 100, height: 100, alignItems: 'center', justifyContent: 'center'}}> <Text style = {{color: "white", fontSize: 20}}>Swipe Me</Text> </View> </TouchableOpacity> ); }; const renderBack = () => { return( <View style = {{backgroundColor:'blue', width: 100, height: 100, alignItems: 'center', justifyContent: 'center'}}> <Text style = {{color: "white", fontSize: 30}}>{props.val}</Text> </View> ); }; return( <SafeAreaView style = {{flex: 1, alignItems: 'center', justifyContent: 'center'}}> {/* 宽高调整为和卡片匹配,ref绑定当前组件的独立ref */} <GestureFlipView ref = {flipRef} width={100} height = {100}> {renderFront()} {renderBack()} </GestureFlipView> </SafeAreaView> ); } export default Cards;
Card List组件(仅修改传参部分)
// 其余代码保持不变,仅修改FlatList的renderItem传参 <FlatList data={DATA} renderItem={({ item }) => ( <View style={styles.itemContainer}> {/* 把item.value改为item.title */} <Cards val = {item.title}/> </View> )} keyExtractor={item => item.id} numColumns={numColumns} />
内容的提问来源于stack exchange,提问作者AKHIL OMAR
相关产品推荐
相关产品推荐

