React Native使用KeyboardAwareScrollView报_this.scroll=ref错误
错误根因
undefined is not an object (evaluating '_this.scroll = ref') 报错直接原因是 函数组件内非法使用类组件专属的this关键字。
Expo CLI 45默认生成的组件是函数组件,不存在组件实例this,KeyboardAwareScrollView挂载时执行innerRef回调,尝试给不存在的this挂载scroll属性就会直接触发崩溃,ref回调执行时机在组件挂载阶段,因此会表现为进入页面偶现闪退。
另外现有代码还存在几个会导致功能异常的问题:
KeyboardAwareScrollView直接嵌套TouchableWithoutFeedback会导致内部内容高度计算异常,滚动失效- 安卓端未开启适配开关,部分机型会出现键盘遮挡输入框的问题
- 额外引入
KeyboardAvoidingView会和组件自带的键盘适配逻辑冲突,导致布局偏移
修复方案
如果使用函数组件(Expo默认开发范式),用React内置的useRef存储滚动实例,同时修正组件嵌套结构即可:
import { useRef } from 'react'; import { TouchableWithoutFeedback, Keyboard, View } from 'react-native'; import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'; const YourPage = () => { const scrollRef = useRef(null); return ( <> <KeyboardAwareScrollView keyboardShouldPersistTaps="always" style={{ flex: 1, backgroundColor: 'white' }} showsVerticalScrollIndicator={false} innerRef={(ref) => { scrollRef.current = ref; }} extraScrollHeight={20} enableOnAndroid={true} > <TouchableWithoutFeedback onPress={Keyboard.dismiss}> <View style={{ flex: 1, paddingHorizontal: 16 }}> {/* 页面内容、输入框放在此处 */} </View> </TouchableWithoutFeedback> </KeyboardAwareScrollView> <Menu /> </> ); }; export default YourPage;
如果使用类组件开发,只需要在类构造函数中提前声明scroll属性,或者直接用React.createRef绑定即可,不要在无实例的作用域下访问this。
效果验证
修复后可实现两个预期效果:
- 输入框聚焦时组件自动计算键盘高度,滚动到对应输入框位置,不会被键盘遮挡
- 点击页面任意非输入框区域,会自动触发键盘收起逻辑
内容的提问来源于stack exchange,提问作者Antonio Rodríguez
相关产品推荐
相关产品推荐

