所有子元素都从React上的父div继承onclick事件

时间:2017-07-29 09:47:06

标签: reactjs events

这是我在返回部分的代码。所有子元素都是无效的点击事件,当我点击它时,它给了我那个子元素的对象而不是父元素。

return (
  <div className={css(style.cell)} onClick={this.props.onClickHandle}>

      <div className={css(style.image)}>
        <CircleImage size={50} url = {"http://www.ruralagriventures.com/wp-content/uploads/2017/05/man-team.jpg"}/>
      </div>

      <div className={css(style.info)}>

        <div className={css(style.profile)}>
          <span>{this.props.name}</span>
          <span className={css(style.lastMessage)}>Latest Message</span>
        </div>

        <div className={css(style.detail)}>
          <span>a few seconds ago</span>
          <span className={css(style.counter)}>5</span>
          </div>
      </div>
  </div>
)

我只想要来自父div的对象,而不是孩子。在传递道具之前 我分配了this.onClickHandle = this.onClickHandle.bind(this);

1 个答案:

答案 0 :(得分:1)

您可以使用refs,请参阅此link

onClickHandle(e){
    this.parentDiv //parent object
}

return (
  <div ref={(parentDiv) => { this.parentDiv = parentDiv; }} className={css(style.cell)} onClick={this.props.onClickHandle}>

      <div className={css(style.image)}>
        <CircleImage size={50} url = {"http://www.ruralagriventures.com/wp-content/uploads/2017/05/man-team.jpg"}/>
      </div>

      <div className={css(style.info)}>

        <div className={css(style.profile)}>
          <span>{this.props.name}</span>
          <span className={css(style.lastMessage)}>Latest Message</span>
        </div>

        <div className={css(style.detail)}>
          <span>a few seconds ago</span>
          <span className={css(style.counter)}>5</span>
          </div>
      </div>
  </div>
)