Using onClick in react.js

时间:2017-05-16 09:18:00

标签: javascript reactjs button onclick

I want to add a comment each time I click the button, here is my addComment fucntion

addComment: function(text){
            console.log('adding');
            var arr = this.state.comments;
            arr.push(text);
            this.setState({comments:arr});
            },

and my render

render: function(){
        return(
        <div>
            <button onCLick={this.addComment.bind(null,'new')} className="button-info create">Add new</button>
            <div className="board">{
            this.state.comments.map(this.eachComment)}
            </div>
        </div>
        );
        }

the whole code is here: https://ghostbin.com/paste/895eb

the problem is there is no error showing in my console and when I click the button, nothing happens.

Can anyone help me find the bug please?

3 个答案:

答案 0 :(得分:0)

This should help you. I think problem i you used onCLick instead of onclick https://facebook.github.io/react/docs/handling-events.html

答案 1 :(得分:0)

你不需要绑定(this)或者什么都可以运行,而是尝试使用将处理的箭头函数(ECMA SCRIPT arrow function)(_this,_self,_that,...)

addComment(text){
            console.log('adding');
            var arr = this.state.comments;
            arr.push(text);
            this.setState({comments:arr});
}
        <div>
            <button onCLick={() => addComment('new')} className="button-info create">Add new</button>
            <div className="board">{
            this.state.comments.map(this.eachComment)}
            </div>
        </div>

答案 2 :(得分:0)

它应该是onClick而不是onCLick。

<button onClick={this.addComment.bind(null,'new')} className="button-info create">Add new</button>

以下是解决方案:https://jsfiddle.net/jayesh24/td1v0kh4/