考虑这个组件:
<Card onClick={openWindowHandler}>
<Editable onDoubleClick={enableInputHandler} />
</Card>
我想要实现的是仅在调度事件时停止事件传播onDoubleClick
因此不调用openWindowHandler
函数。但是,onClick
会在onDoubleClick
之前开火!
我可以通过应用函数来区分调用_.debounce
事件类型,但那时事件已经调度,因此无法调用stopPropagation()
。
class App extends React.Component {
delayedCallback = _.debounce(function (event) {
if (event.type === 'dblclick') {
// too late to call event.stopPropagation()
} else {
// continue
}
}, 250)
handleClick = (event) => {
event.persist()
this.delayedCallback(event)
}
render () {
return (
<Card onClick={this.handleClick}>
<Editable onDoubleClick={this.handleClick} />
</Card>
)
}
}
有什么办法吗?
编辑:单击<Editable />
元素应该冒泡给父母,导致openWindowHandler
调用。
示例:
// This will return a event
function clickHandlerModule() {
var clickCount = 0;
var timer = null;
var delay = 250;
return function(event) {
clickCount++;
if(clickCount === 1){
timer = setTimeout(function(){
console.log('SINGLE CLICK');
clickCount = 0;
}, delay);
} else {
clearTimeout(timer);
console.log('DOUBLE CLICK');
clickCount = 0;
}
}
}
class App extends React.Component {
constructor() {
super();
this.clickHandler = clickHandlerModule()
}
render () {
return (
<Card onClick={this.clickHandler}>
<Editable />
</Card>
)
}
}
export class Sample {
clickCount = 0;
onItemClick() {
let isDoubleClick = false;
this.clickCount++;
if (this.clickCount === 1) {
setTimeout(() => {
if (this.clickCount > 1) {
isDoubleClick = true;
console.log('dblclick');
}
this.clickCount = 0;
if (!isDoubleClick) {
console.log('click');
}
}, 250);
}
}
}
}
.HTML
<Card (click)="onItemClick()">
<Editable (dblclick)="SomeMethodForDblClick()" />
</Card>
因此,您可以在cart.component上为click&&dblClick事件编写一些方法,并将dblclick用于可编辑的组件,而不会发生冲突
附言是的,我正在使用角度,对不起语法:)