2016-08-23 56 views
8

我有一个非常简单的反应成分:为什么ref按钮会被点击3次?

import React, {Component} from 'react'; 

class Hello extends Component { 
    render() { 
    return <div> 
     <h1>Hello Freewind</h1> 
     <div> 
     <button ref="button1" onClick={() => alert('1')}>Click 1</button> 
     <button ref="button2" onClick={() => alert('2')}>Click 2</button> 
     </div> 
     <div> 
     <button onClick={this._clickBoth.bind(this)}>Click both</button> 
     </div> 
    </div>; 
    } 

    _clickBoth() { 
    this.refs.button1.click(); 
    this.refs.button2.click(); 
    } 
} 

export default Hello; 

当你点击“点击这两个”按钮,将“点击1”和“2点击”按钮将被编程点击。奇怪的是,我会看到6个警报:

1 
2 
1 
2 
1 
2 

1 
2 

但如果我删除任何行_clickBoth,比如说,删除this.refs.button2.click();,它将正确behaive和只显示一个警告:

1 

你可以看到,在这里尝试项目:https://github.com/js-demos/react-ref-demo

+1

你能设置上的jsfiddle什么的演示? – Chris

+1

我已经转载了这个问题。有趣的,的确如此。 –

+0

另一个奇怪的事情是,'click'事件的累积速度取决于您模拟事件的参考数量。 –

回答

1

我不确定有什么问题,但我一定希望了解它背后的技术问题。

在此期间,如果你正在寻找一种方式来解决它,你可以用按钮点击里面setTimeout,就像这样:

setTimeout(() => { 
    this.refs.button1.click(); 
    this.refs.button2.click(); 
}, 0); 
0

而且不知道是怎么回事,但我增加了的console.log到_clickBoth处理程序,并得到如下结果:

click both 
click both 
click both 
1 
2 
1 
click both 
click both 
2 
1 
2 
相关问题