React Native中点击搜索图标后如何自动呼出键盘?
解决方案
核心问题是你没有绑定TextInput的引用(ref),无法主动控制输入框的聚焦/失焦状态,按以下步骤修改即可:
完整修改后代码
import { useRef } from 'react'; import { Animated, Dimensions, Keyboard, SafeAreaView, View, TouchableWithoutFeedback, Image } from 'react-native'; // 此处保持你原有导入Input、Container、图标组件的逻辑不变 export default function SearchBar() { const animation = new Animated.Value(50); const { width } = Dimensions.get('window'); const keyboard = useKeyboard(); // 新增:定义输入框的ref引用 const inputRef = useRef(null); function onSearch() { Animated.spring(animation, { toValue: width * 1, useNativeDriver: false, // 新增:动画完全结束后让输入框聚焦,自动唤起键盘 }).start(() => { inputRef.current?.focus(); }); } function onSearchClose() { Animated.spring(animation, { toValue: width * 0.11, useNativeDriver: false, }).start(); // 输入框失焦+全局收起键盘,双重保障生效 inputRef.current?.blur(); Keyboard.dismiss(); } return ( <SafeAreaView style={{ flex: 1, alignItems: 'flex-end', justifyContent: 'center' }}> <View style={{ flexDirection: 'row', justifyContent: 'flex-end' }}> <View style={{ marginRight: 0, justifyContent: 'center' }}> <TouchableWithoutFeedback> <Image source={require('./logo.png')} style={{ width: 30, height: 30 }} /> </TouchableWithoutFeedback> </View> <View style={{ marginRight: 0 }}> <Container style={{ width: animation }}> {/* 新增:给Input绑定ref */} <Input ref={inputRef} placeholder={'search'} style={{ marginLeft: 50, fontSize: 18 }} /> <BoxButtonClose onPress={onSearchClose}> <CloseIcon /> </BoxButtonClose> <BoxButtonSearch onPress={onSearch}> <SearchIcon /> </BoxButtonSearch> </Container> </View> </View> </SafeAreaView> ); }
注意事项
- 如果你代码里的
Input是自行封装的自定义组件,需要使用forwardRef将外部传入的ref透传给内部的原生TextInput组件,否则无法调用focus和blur方法 - 把
focus逻辑放在动画的结束回调里执行,可避免输入框还未完全展开就聚焦导致的布局异常、唤起失败问题
内容的提问来源于stack exchange,提问作者John Ocean
相关产品推荐
相关产品推荐

