没有调用React JS onClick方法

时间:2017-01-24 17:14:40

标签: javascript reactjs

我是React JS的新手,我只是捡起它。这是我的代码:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>React - Component</title>
<script src="../../js/react.min.js"></script>
<script src="../../js/react-dom.min.js"></script>
<script src="../../js/browser.min.js"></script>
</head>
<body>
<div id="container"></div>
<script type="text/babel">
  var Comment= React.createClass({
    edit:function(){
        alert('Editing comment');
      },
    remove:function(){
        alert('Remove comment');
      },
    render:function(){
      return(
        <div classname="commentContainer">
         <div classname="commentText">Whatever</div>
            <button classname="button-primary" onclick={this.edit}>Edit</button>
            <button classname="button-danger" onclick={this.remove}>Delete</button>
        </div>
      );
    }
  });

  ReactDOM.render(
  <div classname="board">
    <Comment>LOL</Comment>
  </div>,
   document.getElementById('container')
  );
</script>

当我单击浏览器中的编辑/删除按钮时,它们不会显示警告对话框。我在代码中做错了什么?

2 个答案:

答案 0 :(得分:2)

React事件处理程序需要在camelCase中: onClick(注意大写'C')

答案 1 :(得分:0)

您应该使用onClick而不是onclick。请参阅下面的工作代码。

详细了解处理反应here

中的事件

  var Comment= React.createClass({
    edit:function(){
        alert('Editing comment');
      },
    remove:function(){
        alert('Remove comment');
      },
    render:function(){
      return(
        <div classname="commentContainer">
         <div classname="commentText">Whatever</div>
            <button classname="button-primary" onClick={this.edit}>Edit</button>
            <button classname="button-danger" onClick={this.remove}>Delete</button>
        </div>
      );
    }
  });

  ReactDOM.render(
  <div classname="board">
    <Comment>LOL</Comment>
  </div>,
   document.getElementById('container')
  );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>React - Component</title>
</head>
<body>
<div id="container"></div>