我知道之前也曾问过类似的问题。但是这次的例子有点不同,所以请忍受我。
我正在尝试在访问键盘侦听器时在react-native组件内部设置状态-
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});
}
我遇到了错误-
我在这里做什么错了?
答案 0 :(得分:2)
您需要授予这些功能访问this
的权限。
您有2种方法:
1)使用箭头功能
_keyboardDidShow = () => {
alert('Keyboard Shown');
this.setState({keyboardOpen: true});
}
_keyboardDidHide = () => {
alert('Keyboard Hidden');
this.setState({keyboardOpen: false});
}
2)在构造函数中使用bind
绑定它们:
constructor(props){
super(props)
this._keyboardDidShow = this._keyboardDidShow.bind(this)
this._keyboardDidHide = this._keyboardDidHide.bind(this)
}
您没有将它们正确绑定到componentDidMount