React Native中嵌套Touchable组件如何实现触摸事件传播?
嘿,这个问题我之前也碰到过!默认情况下React Native的触摸组件(比如TouchableHighlight)会拦截触摸事件,所以点击内层的时候外层的onPress不会触发。要实现你要的效果,有几个可行的办法:
方法1:手动调用外层的事件处理函数
最直接的方式就是把外层的点击逻辑抽成独立函数,然后在内层的点击回调里同时调用外层的函数和内层自己的逻辑。这种方式完全由你控制触发顺序和逻辑,简单易懂:
import React from 'react'; import { TouchableHighlight, Text, View } from 'react-native'; const App = () => { // 抽离外层点击逻辑 const handleOuterPress = () => { console.log('outer press'); }; const handleInnerPress = () => { console.log('inner press'); // 手动触发外层的点击逻辑 handleOuterPress(); }; return ( <TouchableHighlight style={{ flex: 1, backgroundColor: '#eee' }} onPress={handleOuterPress}> <TouchableHighlight style={{ flex: 0.8, backgroundColor: 'blue', margin: 20 }} onPress={handleInnerPress}> <Text style={{ color: 'white', fontSize: 24, textAlign: 'center', padding: 20 }}>1</Text> </TouchableHighlight> </TouchableHighlight> ); }; export default App;
方法2:通过Ref调用外层触摸组件的触发逻辑
如果外层的逻辑不方便抽离,你可以给外层TouchableHighlight加个Ref,然后在内层的点击回调里通过Ref直接调用外层的点击处理函数:
import React, { useRef } from 'react'; import { TouchableHighlight, Text, View } from 'react-native'; const App = () => { const outerTouchableRef = useRef(null); return ( <TouchableHighlight ref={outerTouchableRef} style={{ flex: 1, backgroundColor: '#eee' }} onPress={() => console.log('outer press')} > <TouchableHighlight style={{ flex: 0.8, backgroundColor: 'blue', margin: 20 }} onPress={() => { console.log('inner press'); // 通过Ref触发外层的点击逻辑 outerTouchableRef.current?.onPress(); }} > <Text style={{ color: 'white', fontSize: 24, textAlign: 'center', padding: 20 }}>1</Text> </TouchableHighlight> </TouchableHighlight> ); }; export default App;
注意事项
别想着像Web那样靠事件冒泡解决——React Native的触摸系统和Web不一样,Touchable系列组件默认会拦截触摸事件,而且没有类似stopPropagation的反向操作。所以上面两种手动触发的方式是最可靠的方案。
内容的提问来源于stack exchange,提问作者mannok
相关产品推荐
相关产品推荐

