在本机导航时检测键盘开启模式

时间:2018-08-15 12:15:22

标签: react-native

在我的本机应用程序的注册过程中,我必须从电子邮件屏幕导航到密码屏幕等。当我从电子邮件屏幕单击NEXT时,当我进入密码屏幕时,键盘仍处于打开状态。导航到新屏幕时,如何检测键盘是打开还是关闭?

进入密码屏幕后,键盘监听器将正常工作。这是我的代码。唯一的问题是,加载屏幕时我无法检测到键盘状态。

 constructor(props) {
        super(props);

        this.state = {
            email: {
                value: "",
                valid: false,
                touched: false,
                validationRules: {
                    isEmail: true
                }
            },
            headerStyles: {
                marginTop: 30,
                marginBottom: 70,
                marginLeft: 20
            },
            buttonTouched: false,
            emailAlreadyTaken: false
        }
    }

    // componentDidMount
    componentDidMount() {
        this.keyboardDidShowListener = Keyboard.addListener("keyboardDidShow", this._keyboardDidShow);
        this.keyboardDidHideListener = Keyboard.addListener("keyboardDidHide", this._keyboardDidHide);
    }

    // componentWillMount
    componentWillUnmount() {
        this.keyboardDidShowListener.remove();
        this.keyboardDidHideListener.remove(); 
    }

    // If the keyboard is visible
    _keyboardDidShow = () => {
        this.setState({
            headerStyles: {
                marginTop: 10,
                marginBottom: 30,
                marginLeft: 20
            } 
        });
    }

    // If the keyboard is not visible
    _keyboardDidHide = () => {
        this.setState({
            headerStyles: {
                marginTop: 30,
                marginBottom: 70,
                marginLeft: 20
            }
        });
    }

    // navigation options
    static navigationOptions = () => {
        return {
            headerTitle: null,
            headerStyle: {
                backgroundColor: "white"
            }
        };
    };

导航到新屏幕时如何检测键盘状态?

1 个答案:

答案 0 :(得分:0)

// If the keyboard is visible
_keyboardDidShow = () => {
    this.setState({
        keyBoardIsOn: true, // SET TO FALSE KEYBOARD SHOWN
        headerStyles: {
            marginTop: 10,
            marginBottom: 30,
            marginLeft: 20
        } 
    });
}

// If the keyboard is not visible
_keyboardDidHide = () => {
    this.setState({
        keyBoardIsOn: false, // SET TO FALSE KEYBOARD HIDDEN
        headerStyles: {
            marginTop: 30,
            marginBottom: 70,
            marginLeft: 20
        }
    });
}

_navigate = () = {
    if(this.state.keyBoardIsOn) {
        // Do Stuff
    }
}