【问题标题】:Getting "setState is not a function" in React Native when attempting to fire a function from a listener尝试从侦听器触发函数时在 React Native 中获取“setState 不是函数”
【发布时间】:2017-06-28 15:11:25
【问题描述】:

当键盘向上滑动时,我试图在我的应用程序上隐藏一个徽标。不幸的是,键盘避免视图使徽标看起来很糟糕,所以我宁愿完全隐藏徽标。

我目前的设置是这样的:

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>
}

但是,在此设置中,我得到一个红色屏幕,指出“this.setState 不是函数”。我认为这可能是因为我将函数附加到侦听器,因为 this.setState 在此组件的其他地方正常工作,但我不确定如何将返回的状态从侦听器冒泡到组件的状态。

【问题讨论】:

    标签: react-native


    【解决方案1】:

    您需要致电this.listener.bind(this)s =&gt; this.listener(s)

    这是因为 JavaScript 将 Keyboard 作为 this 传递,而 Keyboard 没有 _keyboardDidShow 方法

    相关:How does the "this" keyword work?

    还相关:Use of the JavaScript 'bind' method

    【讨论】:

    • 你可能是对的,但我认为你可以在这个答案上付出更多的努力,或者更好地找到许多重复项之一。
    • 为你修复了它:p
    【解决方案2】:

    您可以将此函数定义为箭头函数。 例如-

    _keyboardDidShow = () => { 这个.setState({ 标志显示:假 }); }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-26
      • 2013-05-18
      • 1970-01-01
      相关资源
      最近更新 更多