React onClick event

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-30 17:23:55

I think you're going about this wrong, because ReactJS is just JavaScript I don't think your way of firing this event will work. Your onClick should fire a function attached to your React element like so.

var Hello = React.createClass({
    myClick: function () {
        alert("Hello World!");
    },
    render: function() {
        return <button onClick={this.myClick}>
                   Click Me
                </button>;
    }
});

React.render(<Hello />, document.getElementById('container'));

Note: this is another way to do it if you want something quick/inline:

<button onClick={()=>{ alert('alert'); }}>alert</button>

If the function to be run has parameters, is has to be bound to the function as follows:

var Hello = React.createClass({
  handleClick: function (text) {
      alert(text)
  },

   render: function () {
      return <button onClick = {
          this.handleClick.bind(null, "Hello World")
      } > Click Me < /button>;
  }
});

React.render(<Hello / > , document.getElementById('container'));

This makes sense now. Thanks again @Chris-Hawkes for pointing me in the right direction.

Now I see why I had the problem before. The problem came when I was trying to pass an argument to the function:

var Hello = React.createClass({
    myClick: function (text) {
        alert(text);
    },
    render: function() {
        return <button onClick={this.myClick("Hello world")}>
                   Click Me
                </button>;
    }
});

This has the same behavior as the original code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!