React Native升级至SDK 42后CustomDrawerContentComponent功能异常排查
嘿,我看你升级到RN SDK42后,自定义抽屉组件出了只显示图片、菜单不见的问题——注释掉contentComponent就正常,这说明问题肯定出在你的自定义组件里。我帮你梳理下几个关键的修复点:
1. 先把函数组件里的this用错的问题改了!
你的CustomDrawerContentComponent是个函数组件,但你居然用了this.logoImgRef——这是类组件的写法啊!函数组件里根本没有this,得换成React的useRef钩子才行:
// 别忘了先导入useRef import { useRef } from 'react'; const CustomDrawerContentComponent = (props) => { // 用useRef创建图片引用,代替this const logoImgRef = useRef(null); return ( <ScrollView> <Container style={styles.container}> <Header style={styles.drawerHeader}> <Body style={styles.headerBody}> <Image ref={logoImgRef} // 直接用创建好的ref style={{ width: 120, height: 120, marginTop:10}} source={imgLogo} /> </Body> </Header> <Content> <DrawerItems {...props}/> </Content> </Container> </ScrollView> ) }
2. 检查DrawerItems的导入是否正确
在RN SDK42对应的React Navigation v4版本里,DrawerItems是从react-navigation-drawer包导入的,你得确保导入语句没写错:
import { DrawerItems } from 'react-navigation-drawer';
要是你不小心升级到了React Navigation v5+(毕竟SDK升级可能连带依赖升级),那DrawerItems已经被替换成DrawerContentScrollView和DrawerItemList了,得改成这样:
import { DrawerContentScrollView, DrawerItemList } from '@react-navigation/drawer'; // 自定义组件里替换原来的DrawerItems <DrawerContentScrollView {...props}> {/* 你的头部图片区域 */} <DrawerItemList {...props} /> </DrawerContentScrollView>
3. 确认Native Base组件是否兼容SDK42
看你用了Container、Header这些Native Base的组件,得确认你的Native Base版本和RN SDK42兼容不。要是版本不对,很可能会导致布局异常,菜单被挤没或者遮住。要么升级Native Base到兼容版本,要么干脆换成RN原生的View组件试试,比如:
import { View, Image, ScrollView } from 'react-native'; const CustomDrawerContentComponent = (props) => { const logoImgRef = useRef(null); return ( <ScrollView> <View style={[styles.container, { padding: 15 }]}> <View style={[styles.drawerHeader, { alignItems: 'center', marginBottom: 20 }]}> <Image ref={logoImgRef} style={{ width: 120, height: 120, marginTop:10}} source={imgLogo} /> </View> <View> <DrawerItems {...props}/> </View> </View> </ScrollView> ) }
4. 排查样式是否遮挡了菜单
最后,你可以暂时把自定义样式都注释掉,看看菜单能不能正常显示——有时候overflow: hidden或者过高的zIndex会把菜单给遮住。要是注释样式后正常了,就逐个加回去排查哪个样式出问题了。
按上面的步骤改完,应该就能搞定抽屉导航只显示图片的问题啦!
内容的提问来源于stack exchange,提问作者Muditha

