'这'在Keyboard侦听器事件中返回全局范围

时间:2017-10-22 12:27:00

标签: javascript react-native

我正在尝试听键盘开/关事件,使用来自' react-native'的键盘模块,听众可以工作但是在接收器上我无法访问状态因为'这个'引用全局得分而不是此组件'此'。

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)记录为例外: enter image description here 但是keyboardDidShow()中的第二个记录了这个(它继续): enter image description here

问题:如何更改键盘监听器中的状态?

这是因为键盘侦听器功能实际上可能是静态的吗?

1 个答案:

答案 0 :(得分:2)

您希望在传递方法引用时绑定范围,并在其他上下文中调用该方法。您可以像这样使用bind

this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow.bind(this));

或者,您可以使用保留"此"的上下文的箭头功能。关键字。

this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', () => {
    this._keyboardDidShow(<method params>)
});