3

Im attempting to hide a logo on my app when the keyboard slides up. Unfortunately the Keyboard Avoiding View makes the logo look bad, so I rather just hide the logo entirely.

My current set up is this:

import React, { Component } from 'react';
...
import {
    TextInput,
    Keyboard,
    ...
} from 'react-native';


class Login extends Component {
    constructor(props) {
        super(props);
        this.state = {
            ...,
            logoShow: true
        };
    }

    _keyboardDidShow () {
        this.setState({
            logoShow: false
        });
    }

    _keyboardDidHide () {
        this.setState({
            logoShow: true
        });
    }

    ...

    componentWillMount(){
        this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow);
        this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);
    }

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

    ...

    render() {
        ...
        <View>
            <TextInput style={...}
                       ...
                       onSubmitEditing={Keyboard.dismiss}

            />
        </View>
}

However in this set up, I get a red screen stating that "this.setState is not a function". I THINK this might be because Im attaching the function to the listener as this.setState works correctly in other places in this component, but I am unsure how to bubble up the returned state from the listener to the component's state.

JSArrakis
  • 777
  • 1
  • 9
  • 22

2 Answers2

4

You need to call this.listener.bind(this) or s => this.listener(s)

It's because JavaScript is passing Keyboard as this and Keyboard doesn't have a _keyboardDidShow method

Related: How does the "this" keyword work?

Also related: Use of the JavaScript 'bind' method

azium
  • 20,056
  • 7
  • 57
  • 79
woodpav
  • 1,917
  • 2
  • 13
  • 26
1

You can define this function as an arrow function. Eg -

_keyboardDidShow = () => { this.setState({ logoShow: false }); }