React函数组件中无法访问react-native-gesture-handler的Swipeable方法怎么办?
在React函数组件中使用React-Native-Gesture-Handler的Swipeable方法
嘿,我懂你遇到的问题了——React Native Gesture Handler的官方文档里Swipeable都是用类组件的this来调用close()这类方法,换成函数组件确实得换个思路,别担心,用useRef钩子就能完美解决!
核心方案:使用useRef获取Swipeable实例
函数组件里没有this上下文,我们可以借助React的useRef钩子来保存Swipeable组件的实例引用,通过这个引用就能直接调用它的close()、open()等方法了。
下面是完整的代码示例:
import React, { useRef } from 'react'; import { Swipeable, RectButton, View, Text } from 'react-native-gesture-handler'; const SwipeableListItem = () => { // 创建ref对象,用来存储Swipeable组件的实例 const swipeableRef = useRef(null); // 自定义处理关闭的函数,调用ref中的close方法 const handleCloseSwipeable = () => { // 先判断ref是否存在,避免组件未挂载时调用报错 if (swipeableRef.current) { swipeableRef.current.close(); } }; return ( <Swipeable // 将ref绑定到Swipeable组件上 ref={swipeableRef} // 渲染左侧滑动操作按钮 renderLeftActions={() => ( <RectButton style={{ backgroundColor: '#2ecc71', padding: 15, justifyContent: 'center' }} onPress={handleCloseSwipeable} > <Text style={{ color: 'white', fontWeight: 'bold' }}>关闭</Text> </RectButton> )} > {/* 滑动组件的主体内容 */} <View style={{ padding: 20, backgroundColor: 'white', borderBottomWidth: 1, borderColor: '#eee' }}> <Text>可滑动的列表项</Text> </View> </Swipeable> ); }; export default SwipeableListItem;
关键说明
swipeableRef.current就相当于类组件中的this,它指向Swipeable组件的实例,所有官方文档里提到的实例方法都能通过它调用- 调用方法前最好加个
if (swipeableRef.current)的判断,避免组件还没挂载完成时调用方法导致的null报错
内容的提问来源于stack exchange,提问作者gts
相关产品推荐
相关产品推荐

