React Native iOS:TextInput获焦时按钮 onPress 首次点击不触发求助
解决React Native中点击按钮需两次触发的问题
这个问题我之前开发时也碰到过,本质是TextInput处于焦点状态时,第一次点击外部Touchable组件,系统会优先处理TextInput失焦(收起键盘),而不会触发Touchable的onPress事件。下面是具体的解决办法:
步骤1:给TextInput添加ref引用
首先需要给你的TextInput组件添加一个ref,这样我们可以主动调用它的blur()方法来让它失去焦点:
<TextInput ref={(input) => { this.passwordInput = input; }} // 添加ref引用 style={{color: "#FFF", borderBottomColor: "#FFF", borderBottomWidth: 1,fontSize:30,padding: 0, paddingRight: 50,height: 40,width: this.state.width*3/4,shadowOffset: { width: 0, height: 0 }, shadowColor: 'black', shadowOpacity: 0.5, shadowRadius: 5}} onChangeText={(passwordInput) => this.showArrow(passwordInput)} value={this.state.passwordInput} placeholder="Vart ska du?" placeholderTextColor="#FFF" />
步骤2:修改onPress逻辑,先失焦再执行业务代码
接下来修改Touchable的onPress回调,先强制让TextInput失去焦点收起键盘,再执行原本的业务逻辑:
<TouchableHighlight underlayColor="rgba(255,255,255,0)" style={{position: "absolute", top: 0, right: 5,}} onPress={() => { // 先让TextInput失去焦点,触发键盘收起 if (this.passwordInput) { this.passwordInput.blur(); } // 再执行原本的搜索按钮点击逻辑 this.onSearchButtonClick(); }} > <Animated.Image source={require("../../img/right-arrow.png")} style={{width:40, height: 40,opacity: this.state.arrowOpacity}}> </Animated.Image> </TouchableHighlight>
额外兜底方案:结合Keyboard API强制收起
如果遇到ref获取失败的特殊情况,还可以结合React Native的KeyboardAPI来强制收起键盘,先导入API:
import { Keyboard } from 'react-native';
然后在onPress中补充:
onPress={() => { Keyboard.dismiss(); // 强制收起键盘 if (this.passwordInput) { this.passwordInput.blur(); } this.onSearchButtonClick(); }}
这样修改后,用户点击箭头按钮时,会同时完成键盘收起和业务逻辑触发,不需要再点击两次了。
内容的提问来源于stack exchange,提问作者Adam Lagevik
相关产品推荐
相关产品推荐

