You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中TouchableOpacity的OnPress事件失效问题求助

解决React Native中TouchableOpacity onPress事件不触发的问题

我来帮你排查一下问题所在,主要有两个关键点导致你的点击事件没正常工作:

1. 高阶函数的调用方式错误

你的navigateToScreen是一个返回函数的高阶函数(定义为(route) => () => { ... }),但你在传递给DrawerItem的onPress时,写法出了问题:

// 错误写法:只调用了navigateToScreen,但没执行它返回的导航函数
onPress={() => this.navigateToScreen('Profile')}

这种写法下,点击时只会执行外层的箭头函数,调用navigateToScreen('Profile')后得到了实际的导航函数,但没有执行它。

修正方式:直接传递navigateToScreen返回的函数即可,因为它本身就是符合onPress要求的回调函数:

// 正确写法:直接传递返回的导航函数
onPress={this.navigateToScreen('Profile')}

如果一定要用箭头函数包裹,需要手动执行返回的函数:

onPress={() => this.navigateToScreen('Profile')()}

2. 部分DrawerItem未传递onPress属性

看你的SideMenu代码,只有第一个My Profile的DrawerItem传了onPress,后面的Card Requests、Search等组件都没有传递这个属性,所以这些条目点击自然不会有任何反应。你需要给所有需要交互的条目都添加对应的onPress:

<DrawerItem onPress={this.navigateToScreen('Profile')} icon={require('../../resources/images/myprofile_icon.png')} title='My Profile'/>
<DrawerItem onPress={this.navigateToScreen('CardRequests')} icon={require('../../resources/images/cardrequest_icon.png')} title='Card Requests'/>
<DrawerItem onPress={this.navigateToScreen('Search')} icon={require('../../resources/images/search_icon.png')} title='Search'/>
<DrawerItem onPress={this.navigateToScreen('MyCards')} icon={require('../../resources/images/add_icon.png')} title='My Cards'/>
<DrawerItem onPress={this.navigateToScreen('SignOut')} icon={require('../../resources/images/signout_icon.png')} title='Sign Out'/>

额外优化建议

你的DrawerItem里把图标和文字分成了两个独立的TouchableOpacity,这样用户需要精准点击图标或文字才会触发事件,体验不太好。可以把整个条目包裹在一个TouchableOpacity里,让整个区域都可点击:

const DrawerItem = (props) => (
  <TouchableOpacity onPress={props.onPress} style={styles.drawerItemContainer}>
    <FastImage source={props.icon} style={styles.icon} />
    <Text style={styles.drawerItemText}>{props.title}</Text>
  </TouchableOpacity>
);

按上面的方法修改后,你的点击事件应该就能正常触发了。

内容的提问来源于stack exchange,提问作者Sumanth Jois

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:43:27