首页 文章

React本机设置状态不起作用

提问于
浏览
2

我正在尝试更新react本机组件中的状态 . 但它的错误,有人可以帮助我 .

我正在使用react-native-cli版本:2.0.1 react-native verions:0.55.4

Here is my code:

import React, { Component } from 'react'

import {
    Button,
    Text,
    View,
} from 'react-native';

export class ToggleButton extends Component {

    state = {
        isDone: false
    };

    onAction() {
        const value = !this.state.isDone;
        this.setState({ isDone: value });

        const newValue = this.state.isDone;
        console.log(newValue);
    }

    render() {
        return (
            <View>
                <Button
                    title="Action"
                    onPress={this.onAction}
                />
            </View>
        )
    }
}

export default ToggleButton;

3 回答

  • 1

    以下是解决方案

    import React, { Component } from 'react'
    
        import {
            Button,
            Text,
            View,
        } from 'react-native';
    
        export class ToggleButton extends Component {
           // Add state in constructor like this
          constructor(props){
            super(props);
            this.state = {
                isDone: false
            };
          }
    
            onAction() {
                const value = !this.state.isDone;
                this.setState({ isDone: value });
    
                const newValue = this.state.isDone;
                console.log(newValue);
            }
    
            render() {
                return (
                    <View>
                        <Button
                            title="Action"
                            // Add function with onPress
                            onPress={() => this.onAction}
                        />
                    </View>
                )
            }
        }
    
        export default ToggleButton;
    
  • 0

    您有三种不同的解决方案 .

    • 在构造函数中绑定您的函数 .

    • 使用实验性公共类字段语法 .

    • 将lambda传递给执行函数 .

    问题是您丢失了对 this 的引用,因为该函数未在原始上下文中执行,因此 this.setState 不是函数,而是未定义的函数 .

    在此页面中有所有方法的示例:https://reactjs.org/docs/handling-events.html

  • 0

    更改

    onPress={this.onAction}
    

    onPress={this.onAction.bind(this)}
    

    检查:this

相关问题