ReactJS: onClick handler not firing when placed on a child component

做~自己de王妃 提交于 2019-11-27 17:23:14

So, the proper way to handle eventing in this case would be to pass the event handler down to the child component. There are a few ways to accomplish what you want, and I might implement this behavior differently (not sure what the use case is), but I wired up an example in JSX for you that demonstrates the typical event handling between Parent and Child Components. You can find it here...

JS Fiddle

Just think of it like this:

var ParentComponent = React.createClass({
    render: function(){
        return (
            <ChildComponent onSomeEvent={this.handleThatEvent} />;
        )
    },
    handleThatEvent: function(e){
         //update state, etc.
    }
});

var ChildComponent = React.createClass({
    render: function(){
        return (
           <input type="button" onClick={this.props.onSomeEvent} value="Click Me!" />
        )
    }
});

You don't need to make a child component if before you call the node you create a var to reference the render's this i.e.

var self = this;

So for example (this is contrived and the var self isn't needed in this case, but in the case of nested return statements it would be required).

var ParentComponent = React.createClass({
    render: function(){
        var self = this;
        return (
            <input type="button" onClick={self.handleThatEvent} value="Click Me!" />;
        )
    },
    handleThatEvent: function(e){
         //update state, etc.
    }
});

Better yet, you could bind this to the function.

var ParentComponent = React.createClass({
    render: function(){
        return (
            this.state.array.map(function(){
              return (<input type="button" onClick={this.handleThatEvent} value="Click Me!" />);
            }.bind(this));
        )
    },
    handleThatEvent: function(e){
         //update state, etc.
    }
});

Or to follow captray's suggestion in the comments

var ParentComponent = React.createClass({
    render: function(){
        return (
            this.state.array.map(function(){
              return (<input type="button" onClick={this.handleThatEvent} value="Click Me!" />);
            }, this);
        )
    },
    handleThatEvent: function(e){
         //update state, etc.
    }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!