reactjs的事件绑定

我在一个组件里绑定了onClick事件,然后在componentDidMount这个生命周期里为body绑定了一个事件,为什么我点击该元素都是先执行body上绑定的事件,再执行我用onClick绑定的事件?
我在想是不是react的事件都是在顶层做了事件委托,如果是这样,我想实现事件冒泡是不是做不了了?

阅读 6.1k
3 个回答

在组件的onClick事件里取消事件委托

body事件是要到componentDidMount绑定没错,我是没看到问题中的代码,大概有用了jQuery的bindunbind,事件的顺序会不正确。

下面的代码经测试过是可以正常有事件冒泡结果,就 按钮->div->body 的顺序,参考看看:


class Application extends React.Component {

  constructor() {
    super()
    this._handleClick = this._handleClick.bind(this)
    this._handleDivClick = this._handleDivClick.bind(this)
  }

  componentDidMount() {
    document.addEventListener('click', this._handleBodyClick)
  }
  
  componentWillUnmount() {
     document.removeEventListener('click', this._handleBodyClick)
  }
  
  _handleBodyClick(e) {
     console.log('body clicked!')
  }
  
  _handleClick(e) {
    console.log("button clicked!")
     //e.stopPropagation()
    //e.nativeEvent.stopImmediatePropagation()
  }

  _handleDivClick(e) {
    console.log("div clicked!")
     //e.stopPropagation()
    //e.nativeEvent.stopImmediatePropagation()
  }

  render() {
    return (
      <div onClick={this._handleDivClick}>
        <button id="elem" onClick={this._handleClick}>Click me!</button>
      </div>
    )
  }
  
}

ReactDOM.render(<Application />, document.getElementById("root"))

参考这里的问答: http://stackoverflow.com/ques...

自己来填坑,在某一个React-Event绑定的事件回调函数中打印e.nativeEvent.currentTarget可以发现结果是#document, 也就是说React的事件机制应该是全部绑定在了document上。
之前在componentDidMount里面通过document.body.addEventListener绑定了点击事件,因为body其实也是document的下级,所以是先执行body绑定的回调函数。
另外即使改成document.addEventListener来绑定点击事件(假设是function1),在ReactElement中使用e.stopPropagation()是无法阻止function1的调用,要想阻止function1调用,可能只能e.nativeEvent.stopImmediatePropagation();

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题