[英]React onclick listener doesn't work as expected
很简单,如果我点击相应的按钮(上/下/重置),我应该制作一个计数器应用程序来递增/递减/重置计数器。
我是 React 的新手,但知道一些 js。
我收到这个错误信息
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>
我究竟做错了什么?
在 JSX 中,您想用大括号将 Javascript 代码括起来,对于属性,您可以省略引号以使用大括号。
每个 onClick 属性都应该用大括号而不是引号括起来:
<button onClick={incrementCounter}>Up</button>
问题未解决?试试以下方法:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.