简体   繁体   中英

react-js subcomponent onclick event does not get invoked

The Container component is the main component ,which in-turn invoked the rendering of User Component. In user render method the <li> items have onClick event.

The onClick events are getting invoked on page load and then never gets invoked the click event.

Container = React.createClass({

mixins: [ReactMeteorData],

getMeteorData(){
    return{
        currentActiveUsers:ActiveUsers.find({}).fetch()
    };
},

getCurrentActiveUsers(){
    return this.data.currentActiveUsers.map((user) => {
        return <User key={user._id} user={user} />
    }); 
},

render(){
    return(
        <div className="container">
            <div className="container-fluid">
              <div className="row">
                <div className="col-xs-1 col-md-2 col-lg-3 columnBorder">
                    <ul>
                        {this.getCurrentActiveUsers()}
                    </ul> 
                </div>
              </div>
            </div>
        </div>
        );
}

}); User = React.createClass({

propTypes:{
    user:React.PropTypes.object.isRequired
},

initiate(){
    console.log("initiated");
},

render(){
    return(
        <li onClick={this.initiate()}>
            {this.props.user.username}
        </li>
    );
}

});

You are invoking the event at the time of defining the onClick . Instead, you need to bind the onClick to the function:

initiate(){
    console.log("initiated");
},

render(){
    return(
        <li onClick={this.initiate}>
            {this.props.user.username}
        </li>
    );
}

So, simply remove the function call () from the this.initiate() .

Otherwise, you are attempting to bind the result of console.log to onClick .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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