React Native中KeyboardAvoidingView设偏移后无法滚动到顶部如何解决
问题根源
使用position行为的KeyboardAvoidingView嵌套在ScrollView内部时,键盘收起后不会自动清除keyboardVerticalOffset对应的顶部偏移,会导致ScrollView的可滚动内容顶部始终保留固定的空白,无法滚动到页面最顶端。
优先推荐解决方案
调整组件嵌套结构,将KeyboardAvoidingView放在外层,同时适配平台的behavior属性,不需要额外监听事件,平台兼容性更好,键盘弹出收起时偏移都会自动计算重置,不会出现滚动不到顶的问题,同时保留键盘适配的正常效果,实现代码如下:
import { Platform } from 'react-native'; const DismissKeyboard = ({children}) => ( <KeyboardAvoidingView style={{ flex: 1 }} keyboardVerticalOffset={Platform.OS === 'ios' ? 50 : 0} behavior={Platform.OS === 'ios' ? 'padding' : 'height'} > <ScrollView style={{flex: 1}} contentContainerStyle={{flexGrow: 1}}> <View style={{flex:1}}> {children} </View> </ScrollView> </KeyboardAvoidingView> );
兼容原有嵌套结构的解决方案
如果确实有业务需求必须保留原有的嵌套逻辑,可以监听键盘收起事件,手动触发ScrollView滚动到顶部,实现代码如下:
import { Keyboard, ScrollView } from 'react-native'; import { useEffect, useRef } from 'react'; const DismissKeyboard = ({children}) => { const scrollRef = useRef(null); useEffect(() => { const keyboardHideListener = Keyboard.addListener('keyboardDidHide', () => { scrollRef.current?.scrollTo({y: 0, animated: true}); }); return () => { keyboardHideListener.remove(); }; }, []); return ( <ScrollView ref={scrollRef} style={{flex: 1}}> <KeyboardAvoidingView style={{ flex: 1 }} keyboardVerticalOffset={50} behavior={"position"} > <View style={{flex:1}}> {children} </View> </KeyboardAvoidingView> </ScrollView> ) };
内容的提问来源于stack exchange,提问作者Guillaume Theret
相关产品推荐
相关产品推荐

