【问题标题】:onClick event not firing in ReactJSonClick 事件未在 ReactJS 中触发
【发布时间】:2017-07-30 21:23:09
【问题描述】:

我需要在 Click 上触发一个事件,即 handleClick。它不适用于图像或任何按钮。

我也试过箭头函数,但也没有用。它也没有抛出任何错误。任何人都可以提出一些建议吗?

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

}

})

【问题讨论】:

  • 添加完整的组件代码。

标签: javascript reactjs onclick


【解决方案1】:

看起来这是“老这个上下文”的问题:)

如果你使用的是可以转换 ES2015 类属性的 babel,你可以这样做:

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

在其他情况下,只需在构造函数中绑定方法:

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

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

【讨论】:

  • 我在使用React.createClass的时候,所有的方法都是自动绑定的,还需要绑定吗?
猜你喜欢
  • 2016-06-23
  • 1970-01-01
  • 2020-01-31
  • 2013-04-30
  • 2011-02-05
  • 1970-01-01
  • 2014-11-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多