【问题标题】:React Nat Counter反应 Nat 计数器
【发布时间】:2015-11-10 12:36:42
【问题描述】:

当点击一个按钮时,我希望一个值每次增加一。我想调用一个函数incrementCounter()为我处理操作,而不是:onPress={() => this.setState({Count: ++this.state.Count})}

这是我目前的课程代码:

class Main extends React.Component{
constructor(props){
    super(props);
    this.state = {
        Count: 0,
    }
}
incrementCounter(){
    this.setState({
        Count: this.state.Count + 1 //!!! Where error occurs
    }); 
}

 render() {
    return(
        <View style={styles.mainContainer}>
            <Text style={styles.title}>{'Count: ' + this.state.Count} </Text>
            <TouchableHighlight
                style={styles.button}
                onPress={this.incrementCounter}
                underlayColor='white'>
                <Text style={styles.buttonText}>+</Text>
            </TouchableHighlight>
        </View>
    )
 }
};

上面的代码导致错误 - 红屏: “undefined is not an object (evalating 'this.state.Count')”,错误出现在 incrementCounter()

我可以在网上找到的大多数示例都没有使用 ES6 语法,但是我想尝试并坚持这一点,以使其在我的应用程序中保持标准。未来的工作将包括有一个 decrementCounter() 函数,它会做相反的事情,但不会让计数器降到零以下。

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    我看到您使用的是 es6 表示法,请尝试以下操作:

     render() {
        return(
            <View style={styles.mainContainer}>
                <Text style={styles.title}>{'Count: ' + this.state.Count} </Text>
                <TouchableHighlight
                    style={styles.button}
                    onPress={this.incrementCounter.bind(this)}
                    underlayColor='white'>
                    <Text style={styles.buttonText}>+</Text>
                </TouchableHighlight>
            </View>
        )
     }
    

    注意事件上的 .bind(this),这是必需的,以便它真正引用类本身而不是某个全局函数。

    【讨论】:

    • 谢谢,它工作得很好,并且也成功地实现了decrementCounter 功能! ES6 React Native 函数有没有好的链接?
    • 不是我真正知道的,但是 babel 的人确实有一篇关于 es6 + react 的很棒的帖子,他们也用绑定显示了这个问题,babeljs.io/blog/2015/06/07/react-on-es6-plus
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-04
    • 1970-01-01
    • 1970-01-01
    • 2023-02-10
    • 1970-01-01
    • 2018-06-28
    相关资源
    最近更新 更多