React Native:键盘弹出时Pressable点击事件无法触发求助
解决React Native搜索列表项需两次点击的问题
问题分析
当输入框聚焦且键盘弹出时,第一次点击列表项会被系统优先处理为收起键盘,而非触发Pressable的点击事件,导致需要两次操作才能完成选择。即使尝试了keyboardShouldPersistTaps属性,仍可能因未结合手动失焦或属性配置不当而无效。
解决方案
通过手动让输入框失焦+**正确配置keyboardShouldPersistTaps**的组合方案,实现一次点击同时收起键盘并触发选择事件:
- 给
TextInput添加引用,在点击列表项时主动调用失焦方法 - 给
FlatList设置keyboardShouldPersistTaps="handled",确保点击事件被组件处理时不被键盘拦截
修改后的完整代码
import { useRef } from 'react'; import { Pressable, KeyboardAvoidingView, SafeAreaView, StatusBar, View, TextInput, FlatList, } from 'react-native'; import { FontAwesomeIcon } from '@fortawesome/react-native-fontawesome'; import { faChevronLeft } from '@fortawesome/free-solid-svg-icons'; import Typography from './Typography'; // 假设Typography是你的自定义组件 interface Props { items: { id: number; label: string }[]; onChange: (itemId: number) => void; value: string; onClose: () => void; } export const List = ({ onChange, items, value, onClose, }: Props) => { const inputRef = useRef<TextInput>(null); const handlePress = (itemId: number) => () => { // 先让输入框失焦,收起键盘 inputRef.current?.blur(); // 触发选择事件 onChange(itemId); }; const renderItem = ({ item }: { item: { id: number; label: string } }) => ( <Pressable onPress={handlePress(item.id)}> <Typography>{item.label}</Typography> </Pressable> ); return ( <KeyboardAvoidingView behavior="padding"> <SafeAreaView> <StatusBar backgroundColor={primaryColor} barStyle="light-content" /> <View> <Pressable onPress={onClose}> <FontAwesomeIcon size={spacingL} icon={faChevronLeft} color={white} /> </Pressable> <TextInput ref={inputRef} value={value} blurOnSubmit autoFocus clearButtonMode="while-editing" /> </View> <View> <FlatList data={items} renderItem={renderItem} keyExtractor={item => item.id.toString()} keyboardShouldPersistTaps="handled" /> </View> </SafeAreaView> </KeyboardAvoidingView> ); };
关键说明
inputRef.current?.blur():主动触发输入框失焦,强制收起键盘,避免系统拦截第一次点击事件keyboardShouldPersistTaps="handled":该配置告诉React Native,当点击事件被子组件(如Pressable)处理时,键盘不会抢占事件优先级,确保点击能直接触发onPress逻辑
内容的提问来源于stack exchange,提问作者Manuel Lemaire
相关产品推荐
相关产品推荐

