Javascript ';这';返回键盘侦听器事件中的全局范围
我正在尝试使用“react native”中的键盘模块侦听键盘开/关事件,侦听器工作,但在接收器上我无法访问状态,因为“this”引用的是全局分数,而不是该组件的“this”Javascript ';这';返回键盘侦听器事件中的全局范围,javascript,react-native,Javascript,React Native,我正在尝试使用“react native”中的键盘模块侦听键盘开/关事件,侦听器工作,但在接收器上我无法访问状态,因为“this”引用的是全局分数,而不是该组件的“this” export default class SignupEmailScreen extends React.Component { constructor(props) { super(props); this.state = { emailText: '',
export default class SignupEmailScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
emailText: '',
continueTextFadeAnim: new Animated.Value(0.4),
continueText: emailInvalidText,
bottomLocation: Layout.window.height,
};
console.log(this)
}
componentWillMount() {
this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow);
this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);
}
componentWillUnmount() {
this.keyboardDidShowListener.remove();
this.keyboardDidHideListener.remove();
}
_keyboardDidShow(endCoordinates) {
console.log(this)
}
_keyboardDidHide() {
}
...
}
构造函数日志中的第一个console.log(this)
,以下情况除外:
但是键盘didshow()
中的第二个记录了这一点(它继续):
问题:如何更改键盘侦听器的状态
这是因为键盘侦听器函数实际上可能是静态的吗?在传递方法引用并在其他上下文中调用该方法时,需要绑定作用域。您可以像这样使用
bind
:
this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow.bind(this));
或者,您可以使用保留“this”关键字上下文的箭头函数
this.keyboardDidShowListener=Keyboard.addListener('keyboardDidShow',()=>{
这个。_keyboardDidShow()
});
只需定义如下函数:\u keyboardDidShow=(endCoordinates)=>{…
this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', () => {
this._keyboardDidShow(<method params>)
});