React onClick event

人盡茶涼 提交于 2019-11-30 00:43:42

问题


I'm missing something. Here's a very simple hello world, the goal is to just fire an alert event onClick. The event does fire when the page loads, but not when I click the button. I appreciate the help. Here's a jsFiddle to make it easier to see: jsFiddle

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

回答1:


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'));



回答2:


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

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



回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/32486191/react-onclick-event

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