简体   繁体   English

React onclick 侦听器未按预期工作

[英]React onclick listener doesn't work as expected

Simple thing, I'm supposed to make a counter app that increments/decrcements/resets a counter if I click on the corresponding button (up/down/reset).很简单,如果我点击相应的按钮(上/下/重置),我应该制作一个计数器应用程序来递增/递减/重置计数器。

I'm new to React but know some js.我是 React 的新手,但知道一些 js。

I get this as error message我收到这个错误信息

Warning: Expected `onClick` listener to be a function, instead got a value of `string` type.
    in button (created by App)
    in div (created by App)
    in div (created by App)
    in App
<script type=text/babel>
    class App extends React.Component {

        constructor(props) {
            super(props)
            this.state = {count: 0} // init count
        }
        
        render() {
            return <div className="counter">
                <div className="title">Counter</div>
                <div className="number">{this.state.count}</div>
                <div className="buttons">
                    <button onClick='incrementCounter()'>Up</button>
                    <button onClick='decrementCounter()'>Down</button>
                    <button onClick='resetCounter()'>Reset</button>
                </div>
            </div>
        }

        // why does this not work?
        incrementCounter(){
            this.setState( state => ({ count: this.state.count + 1 }) )
        }

        decrementCounter(){
            this.setState( state => ({ count: this.state.count - 1 }) )
        }

        resetCounter(){
            this.setState( state => ({ count: 0 }) )
        }
    }
    
    ReactDOM.render(<App/>, document.getElementById("root"))
</script>

What am I doing wrong?我究竟做错了什么?

In JSX, you want to surround Javascript code with curly braces and for attributes, you omit the quotes to use curly brances.在 JSX 中,您想用大括号将 Javascript 代码括起来,对于属性,您可以省略引号以使用大括号。

Each onClick attribute should be surrounded by braces instead of quotes:每个 onClick 属性都应该用大括号而不是引号括起来:

<button onClick={incrementCounter}>Up</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM