简体   繁体   English

在react.js中使用onClick

[英]Using onClick in react.js

I want to add a comment each time I click the button, here is my addComment fucntion 我想在每次单击按钮时添加评论,这是我的addComment功能

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

and my render 和我的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 整个代码在这里: 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? 谁能帮我找到错误?

This should help you. 这应该对您有帮助。 I think problem i you used onCLick instead of onclick https://facebook.github.io/react/docs/handling-events.html 我认为我使用onCLick而不是onclick的问题https://facebook.github.io/react/docs/handling-events.html

you dont need to bind (this) or what ever to function , instead try to use arrow function ( ECMA SCRIPT arrow function ) which will handle (_this, _self, _that , ...) 您不需要绑定(this)或其他函数,而是尝试使用箭头函数( ECMA SCRIPT箭头函数 )来处理(_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>

It should be onClick instead of onCLick. 应该是onClick而不是onCLick。

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

Here is the solution: https://jsfiddle.net/jayesh24/td1v0kh4/ 这是解决方案: https : //jsfiddle.net/jayesh24/td1v0kh4/

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

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