React Native Bottom tabs navigator tabBarButton选项配置后运行报错问题
错误根因
你编写的tabBarButton回调函数未返回可渲染的React元素:箭头函数使用花括号包裹函数体时,需要显式使用return语句返回组件,否则函数返回值为undefined,React Navigation渲染底部标签栏时接收到非法值就会抛出异常。报错偶尔指向useFonts.js属于React Native异常调用栈偏移问题,和实际错误原因无关。
修复方案
有两种写法可选:
方案1:显式添加return语句
<Tab.Screen options={{ tabBarIcon: ({ focused }) => { return ( <TabIcon focused={focused} icon={icons.trade} isTrade label='Trade' /> ); }, tabBarButton: (props) => { // 新增return返回组件 return ( <TouchableOpacity {...props} onPress={(e) => { console.log('wa'); // 保留原有的标签跳转逻辑,不要完全覆盖props.onPress props.onPress?.(e); }}> <Text>Touch</Text> </TouchableOpacity> ); }, }} name='Trade' component={Home} />
方案2:使用箭头函数隐式返回
将函数体的花括号替换为圆括号,无需写return即可自动返回内部组件:
tabBarButton: (props) => ( <TouchableOpacity {...props} onPress={(e) => { console.log('wa'); props.onPress?.(e); }}> <Text>Touch</Text> </TouchableOpacity> ),
内容的提问来源于stack exchange,提问作者Sharofiddin Azizmatov
相关产品推荐
相关产品推荐

