为什么在此反应代码中释放div外部时,不触发mouseup事件(使用window.addEventListener)

时间:2018-12-20 06:02:47

标签: javascript reactjs addeventlistener

任何人都可以突出显示为什么当我单击内部div,将光标(在鼠标按钮保持向下的情况下)拖到div的外部,然后释放按钮时,为什么不触发mouseup事件吗?失败似乎也是断断续续的。

这是一个React Web应用。

import * as React from 'react'
import './App.css'

class App extends React.Component {

  public handleMouseDown = (e:any) => {
    // tslint:disable-next-line:no-console
    console.log('handleMouseDown - add Listeners')      
    window.addEventListener('mouseup', this.handleMouseUp, true)
  }

  public handleMouseUp = (e:MouseEvent) => {
    // tslint:disable-next-line:no-console
    console.log('handleMouseUp - remove Listeners')      
    window.removeEventListener('mouseup', this.handleMouseUp, true);
  };  

  public render() {
    return (
      <div className="App" style={{ border: '1px solid blue', height:300, padding:50 }} >
        Main Div - Top
        <div 
          style={{ border: '1px solid black', height:100 }}
          onMouseDown={this.handleMouseDown}
        >
          Inside Div
        </div>        
        Main Div - Bottom
      </div>
    );
  }
}

export default App;

App.css

.App {
  text-align: center;
}

调试输出:

handleMouseDown - add Listeners
handleMouseUp - remove Listeners
handleMouseDown - add Listeners
handleMouseUp - remove Listeners
handleMouseDown - add Listeners
handleMouseDown - add Listeners
handleMouseDown - add Listeners
handleMouseDown - add Listeners

2 个答案:

答案 0 :(得分:2)

为什么不分别附加活动:

onMouseDown={this.handleMouseDown}
onMouseUp={this.handleMouseUp}

答案 1 :(得分:1)

当我将鼠标从Inside Div拖动到Outside时,我发现,文本被选中并一起移动。这更改了鼠标事件的行为。我尝试将user-select: none;放入.app的CSS中,它可以正常工作。看一下我的代码:

class App extends React.Component {
	constructor() {
    super();
  	this.handleMouseUp = this.handleMouseUp.bind(this);
    this.handleMouseDown = this.handleMouseDown.bind(this);
  }
  handleMouseDown(e){
    console.log('handleMouseDown - add Listeners')      
    window.addEventListener('mouseup', this.handleMouseUp, true)
  }

  handleMouseUp(e) {
    console.log('handleMouseUp - remove Listeners')      
    window.removeEventListener('mouseup', this.handleMouseUp, true);
  } 
  
  render() {
    return (
      <div className="App" style={{ border: '1px solid blue', height:300, padding:50 }} >
        Main Div - Top
        <div style={{ border: '1px solid black', height:100 }} onMouseDown={this.handleMouseDown}>  Inside Divn </div>
        Main Div - Bottom
      </div>
    )
  }
}

ReactDOM.render(
  <App  />,
  document.getElementById('container')
);
.App {
  text-align: center;
  user-select: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="container">
    <!-- This element's contents will be replaced with your component. -->
</div>

希望这会有所帮助。