首页 > 解决方案 > 为什么在我的反应原生应用程序中按下每个键后键盘都会消失?

问题描述

我的代码的主要部分如下,基本上,它允许用户选择一个国家并输入他们的电话号码。一旦电话号码被识别为有效,图标的颜色就会改变。唯一的问题是每次按下数字键盘上的键时键盘都会继续消失。这是一个例子:

在此处输入图像描述

这是电话登录屏幕的源代码。如果没有该行onChangePhoneNumber={ (phone) => {this.updateInfo()} },键盘不会在您键入时消失,但下一个图标不会在键入有效数字时变为蓝色阴影。该函数会在用户键入时更新状态。

import React, { Component } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, TextInput, Keyboard} from 'react-native';
import { Icon } from 'react-native-elements';

import KeyboardAccessory from 'react-native-sticky-keyboard-accessory';
import PhoneInput from 'react-native-phone-input';

export default class PhoneLogin extends Component {

    constructor() {
        super();

        this.state = {
            valid: "",
            type: "",
            value: "",
            iconColor: "#D3D3D3",
        };

        this.updateInfo = this.updateInfo.bind(this);
    }

    updateInfo() {
        this.setState({
            valid: this.phone.isValidNumber(),
            type: this.phone.getNumberType(),
            value: this.phone.getValue().replace(/[- )(]/g,''),
        });
    }

    render() {
        return (
          <View style={styles.container}>
            <PhoneInput
              ref={ref => {
                this.phone = ref;
              }}
              style={{height: 50, borderColor:'#44c0b9', borderBottomWidth:2}}
              onChangePhoneNumber={ (phone) => {this.updateInfo()} }
            />

            <KeyboardAccessory backgroundColor="#fff">
                <View style={{ alignItems: 'flex-end', padding:10 }}>
                    <Icon
                        raised
                        reverse
                        color={(this.state.valid) ? "#44c0b9" : "#D3D3D3"}
                        name='arrow-right'
                        type='font-awesome'
                        onPress={ Keyboard.dismiss()}
                    />
                </View>
            </KeyboardAccessory>
          </View>
        );
    }

}

标签: reactjsreact-native

解决方案


包 react-native-phone-input 有一个名为的函数focus,它基本上将焦点放在文本输入上。在我的代码this.phone = ref;中,所以当我运行时this.phone.focus(),文本输入处于焦点状态并且键盘出现。为了防止键盘消失,我所要做的就是添加以下功能。

componentDidMount(){
    this.phone.focus()
}

推荐阅读