反应功能

时间:2017-04-09 18:37:07

标签: javascript reactjs react-native

我创建了下一个类

export default class WaterCount extends Component {

    static defaultProps = {};

     state = {
        currentVolume: 0
    };

    constructor(props) {
        super(props);

    }


    render() {
        return (

                {/*Start of buttons container*/}
                <View style={styles.buttonsContainer}>
                    <Button onPress={() => {
                        this.setState({
                currentVolume: this.state.currentVolume + 10
            }, function () {
                alert(this.state.currentVolume);
            });
                    }} title="Hi!"/>
                </View>

    }
}

如果我像上面的例子中那样为按钮定义功能,那么一切正常。

但如果我通过这种方式做同样的事情:

export default class WaterCount extends Component {


     static defaultProps = {};

        state = {
            currentVolume: 0
        };

        constructor(props) {
            super(props);

        }


        render() {
            return (

                    {/*Start of buttons container*/}
                    <View style={styles.buttonsContainer}>
                        <Button onPress={this.addVolume} title="Hi!"/>
                    </View>

            );
        }

        addVolume() {
            this.setState({
                currentVolume: this.state.currentVolume + 10
            }, function () {
                alert(this.state.currentVolume);
            });
        }

}

error : undefined is not an object(evaluating 'this.state.currentVolume').你能说我的错误在哪里?

1 个答案:

答案 0 :(得分:1)

 <Button onPress={this.addVolume} title="Hi!"/>

需要

 <Button onPress={this.addVolume.bind(this)} title="Hi!"/>

基本上,对于熟悉React的人来说,这是一个常见的错误。您需要为该方法提供上下文,因为React不会自动为您执行此操作。

了解更多here

或者,您可以在构造函数

中使用以下代码段
this.addVolume = this.addVolume.bind(this);
相关问题