Reputation: 649
I know similar question has been asked before. But this time the example is bit different, so please bear with me.
I am trying to set state inside a react-native component while accessing the keyboard listener -
componentDidMount() {
this.keyboardDidShowListener = Keyboard.addListener(
'keyboardDidShow',
this._keyboardDidShow,
);
this._keyboardDidShow.bind(this);
this.keyboardDidHideListener = Keyboard.addListener(
'keyboardDidHide',
this._keyboardDidHide,
);
this._keyboardDidHide.bind(this);
}
componentWillUnmount() {
this.keyboardDidShowListener.remove();
this.keyboardDidHideListener.remove();
}
_keyboardDidShow() {
alert('Keyboard Shown');
this.setState({keyboardOpen: true});
}
_keyboardDidHide() {
alert('Keyboard Hidden');
this.setState({keyboardOpen: false});
}
I am getting the error -
What am I doing wrong here?
Upvotes: 0
Views: 242
Reputation: 4489
You need to give those functions access to this
.
You have 2 ways:
1) Using arrow function
_keyboardDidShow = () => {
alert('Keyboard Shown');
this.setState({keyboardOpen: true});
}
_keyboardDidHide = () => {
alert('Keyboard Hidden');
this.setState({keyboardOpen: false});
}
2) Binding them using bind
in your constructor:
constructor(props){
super(props)
this._keyboardDidShow = this._keyboardDidShow.bind(this)
this._keyboardDidHide = this._keyboardDidHide.bind(this)
}
You didn't bind them correctly in your componentDidMount
Upvotes: 3