Reactjs 处理同一元素的双击和单次单击的反应
当我向元素添加单个onClick事件以及向同一元素添加onDoubleClick事件时,双击也会触发单次单击。我想把它分开,这样单人或双人只触发一个事件。我在Jquery中找到了一些示例,但我希望为React提供一个干净的函数Reactjs 处理同一元素的双击和单次单击的反应,reactjs,onclick,ondoubleclick,Reactjs,Onclick,Ondoubleclick,当我向元素添加单个onClick事件以及向同一元素添加onDoubleClick事件时,双击也会触发单次单击。我想把它分开,这样单人或双人只触发一个事件。我在Jquery中找到了一些示例,但我希望为React提供一个干净的函数 handleClick = () => { console.log('only fire click') } handleDoubleClick = () => { console.log('only fire double click')
handleClick = () => {
console.log('only fire click')
}
handleDoubleClick = () => {
console.log('only fire double click')
}
render () {
return <Element
onClick={evt => this.handleClick}
onDoubleClick={evt => this.handleDoubleClick}
></Element>
}
handleClick=()=>{
console.log('仅火灾点击')
}
handleDoubleClick=()=>{
console.log('仅消防双击')
}
渲染(){
返回这个。handleClick}
onDoubleClick={evt=>this.handleDoubleClick}
>
}
基于我为jquery找到的其他代码片段,我创建了这个简单的函数,以根据单击生成正确的事件。希望这能帮助其他人做出反应
componentWillMount = props => {
this.clickTimeout = null
}
handleClicks = () => {
if (this.clickTimeout !== null) {
console.log('double click executes')
clearTimeout(this.clickTimeout)
this.clickTimeout = null
} else {
console.log('single click')
this.clickTimeout = setTimeout(()=>{
console.log('first click executes ')
clearTimeout(this.clickTimeout)
this.clickTimeout = null
}, 2000)
}
}
render () {
return <Element
onClick={evt => this.handleClicks}
></Element>
}
componentWillMount=props=>{
this.clickTimeout=null
}
handleClicks=()=>{
如果(this.clickTimeout!==null){
console.log('双击执行')
clearTimeout(此为。单击超时)
this.clickTimeout=null
}否则{
console.log('单击一次')
this.clickTimeout=setTimeout(()=>{
console.log('first click executes')
clearTimeout(此为。单击超时)
this.clickTimeout=null
}, 2000)
}
}
渲染(){
返回这个。handleClicks}
>
}
我希望下面的代码能帮助您单键和双击
constructor(props){
super(props);
this.clickCount = 0;
this.singleClickTimer = '';
}
singleClick = () => {
console.log('only fire click')
}
handleDoubleClick = () => {
console.log('only fire double click')
}
handleClicks(){
this.clickCount++;
if (this.clickCount === 1) {
this.singleClickTimer = setTimeout(function() {
this.clickCount = 0;
this.singleClick();
}.bind(this), 300);
} else if (this.clickCount === 2) {
clearTimeout(this.singleClickTimer);
this.clickCount = 0;
this.handleDoubleClick();
}
}
render () {
return <Element
onClick={() => this.handleClicks()}
></Element>
}
构造函数(道具){
超级(道具);
此参数为0.clickCount=0;
this.singleClickTimer='';
}
单击=()=>{
console.log('仅火灾点击')
}
handleDoubleClick=()=>{
console.log('仅消防双击')
}
手舔{
点击count++;
如果(this.clickCount==1){
this.singleClickTimer=setTimeout(函数(){
此参数为0.clickCount=0;
这是singleClick();
}.绑定(本),300);
}else if(this.clickCount==2){
clearTimeout(这是singleClickTimer);
此参数为0.clickCount=0;
此.handleDoubleClick();
}
}
渲染(){
返回此.handleClicks()}
>
}
作为参考,这很有帮助,谢谢-但我发现我需要在
设置超时之前将调用移动到This.singleClick()
,否则单击函数的效果也会因超时而延迟。