在ReactJS中未触发onClick事件 [英] onClick event not firing in ReactJS

查看:714
本文介绍了在ReactJS中未触发onClick事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 Click 上触发一个事件,即 handleClick .在图像或任何按钮上均不起作用.

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>
        )
    }

}

})

推荐答案

这是个好时机,看起来像这样":)

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

如果您正在使用可以转换ES2015类属性的babel,则可以这样做:

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

更多信息可在此处找到: http://egorsmirnov.me/2015/08/16/react-and-es6-part3.html

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

这篇关于在ReactJS中未触发onClick事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆