[英]React - Prevent onMouseDown event on parent element when a child element is clicked
我有一個帶有onMouseDown事件的父元素,該事件使它可拖動。
在其中,我有幾個絕對定位的帶有onClick事件的子元素。
我曾想過,通過對子元素應用更高的Z-index,onClick將運行,而不是onMouseDown,但是似乎兩者都運行,並且如果div被拖動,onClick事件將無法正常運行。 我試圖阻止事件傳播,但似乎無濟於事。 當子級onClick運行時,如何防止父級onMouseDown被激活?
這是代碼的簡化版本
export default class Day extends Component {
constructor(props) {
super(props);
this.showTalks = this.showTalks.bind(this)
this.state = {isScrolling: false};
this.componentWillUpdate = this.componentWillUpdate.bind(this)
this.toggleScrolling = this.toggleScrolling.bind(this)
this.onScroll = this.onScroll.bind(this)
this.onMouseMove = this.onMouseMove.bind(this)
this.onMouseUp = this.onMouseUp.bind(this)
this.onMouseDown = this.onMouseDown.bind(this)
this.attachScroller = this.attachScroller.bind(this)
this.titleRef = React.createRef();
}
componentWillUpdate = (nextProps, nextState) =>{
if(this.state.isScrolling !== nextState.isScrolling ) {
this.toggleScrolling(nextState.isScrolling);
}
};
toggleScrolling = (isEnable) => {
if (isEnable) {
window.addEventListener('mousemove', this.onMouseMove);
window.addEventListener('mouseup', this.onMouseUp);
window.addEventListener("drag", this.onMouseMove);
} else {
window.removeEventListener('mousemove', this.onMouseMove);
window.removeEventListener("drag", this.onMouseMove);
}
};
onScroll = (event) => {
};
onMouseMove = (event) => {
const {clientX, scrollLeft, scrollTop, clientY} = this.state;
this._scroller.scrollLeft = -(scrollLeft - clientX + event.clientX);
this._scroller.scrollTop = scrollTop - clientY + event.clientY;
};
onMouseUp = () => {
this.setState(
{
isScrolling: false,
scrollLeft: 0,
scrollTop: 0,
clientX: 0,
clientY:0
}
);
};
onMouseDown = (event) => {
const {scrollLeft, scrollTop} = this._scroller;
this.setState({
isScrolling:true,
scrollLeft,
scrollTop,
clientX:event.clientX,
clientY:event.clientY
});
};
attachScroller = (scroller) => {
this._scroller = ReactDOM.findDOMNode(scroller);
};
showTalks(talkApi){
this.props.showTalks( talkApi);
}
render() {
let talksArray = [<Talk></Talk>] //removed code that generates an array of talks
return (
<div
onMouseDown={this.onMouseDown}
onScroll={this.onMouseMove}
className="multi-columns">
{talksArray}
</div>
);
}
}
export default class Talk extends Component {
constructor(props) {
super(props);
this.handleFetch = this.handleFetch.bind(this);
}
handleFetch(e){
e.preventDefault();
e.stopPropagation();
let id = e.currentTarget.dataset.id;
this.props.showTalks(id);
}
render(){
return(
<div
data-id={this.props.id}
onClick={this.handleFetch.bind(this)}
>
<h2>{this.props.title}</h2>
</div>
)
}
}
我意識到e.stopPropagation(); handleFetch()函數上的代碼不起作用,因為我正在使用onClick事件,並且停止傳播該事件對完全獨立的onMouseDown事件沒有影響。
現在,我將onClick切換到另一個onMouseDown事件,然后stopPropagation起作用。 但是我想知道是否有更好的方法可以允許我使用onClick。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.