Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

javascript - onClick event not firing in ReactJS

I need to fire an event on Click i.e handleClick. It's not working either on the image or any button.

I tried arrow functions too but that is also of no use. Neither it is throwing any error. Can anyone suggest something?

let Blips = React.createClass({

handleClick(){
    if (this.props.user_name != null) {
        sessionStorage.setItem('user_name', JSON.stringify(this.props.user_name))
        sessionStorage.setItem('port_id', JSON.stringify(this.props.port_id))
        sessionStorage.setItem('ship_image', JSON.stringify(this.props.ship_image))
        sessionStorage.setItem('port_type', JSON.stringify(this.props.port_type))
        browserHistory.push('/dockedship/')
    }
},
render(){

    if (this.props.user_name) {
        return (
            <li className="layer" data-depth={this.props.data_depth}>
                <div className={this.props.css_location}>
                    <img className="glyphport" onClick={this.handleClick} src={this.props.port_type_image}/>
                    <img className="shipport" src={this.props.ship_image}/>
                </div>
            </li>
        )
    }

}

})

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Looks like this is a problem with "good old this context" :)

If you're using babel which can transpile ES2015 class properties you can do it like:

handleClick = () => {
  // ...
}

In other case just bind method in constructor:

this.handleClick = this.handleClick.bind(this);

More information can be found here: http://egorsmirnov.me/2015/08/16/react-and-es6-part3.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...