Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 单击要触发两次的事件_Javascript_Html_Reactjs - Fatal编程技术网

Javascript 单击要触发两次的事件

Javascript 单击要触发两次的事件,javascript,html,reactjs,Javascript,Html,Reactjs,我将ReactJS用于以下组件: var TypeaheadBox = React.createClass({ _handleClick(e) { if (ReactDOM.findDOMNode(this.refs.typeaheadBox).contains(e.target)) { return; }; this.props.onClickOutside(); }, componentWillMount: function() { doc

我将ReactJS用于以下组件:

var TypeaheadBox = React.createClass({

_handleClick(e) {
    if (ReactDOM.findDOMNode(this.refs.typeaheadBox).contains(e.target)) {
        return;
    };
    this.props.onClickOutside();
},

componentWillMount: function() {
    document.addEventListener('click', this._handleClick, false);
},

componentWillUnmount: function() {
    document.removeEventListener('click', this._handleClick, false);
},

render() {
    return (
        <div id='typeahead-box' ref='typeaheadBox'>
            ...
        </div>
    );
}
});
var TypeaheadBox=React.createClass({
_handleClick(e){
if(ReactDOM.findDOMNode(this.refs.typeaheadBox).contains(e.target)){
返回;
};
this.props.onClickOutside();
},
componentWillMount:function(){
document.addEventListener('click',this.\u handleClick,false);
},
componentWillUnmount:function(){
document.removeEventListener('click',this.\u handleClick,false);
},
render(){
返回(
...
);
}
});
如您所见,我正在为单击事件添加一个侦听器。调试时,我意识到当发生单击事件时,_handleClick函数被调用两次,而且在第二次调用中,this.refs字段为空,因此引发了一个错误


我做错了什么?

有多少次,
componentWillMount
被调用了它也被调用了两次。想想看,我在我的页面中使用了两次这个组件。这就是为什么调用了两次
\u handleClick
。。每次调用
componentWillMount
时,它都会向documetn对象添加一个新的单击处理程序
componentWillMount
被调用了多少次它也被调用了两次。想想看,我在我的页面中使用了两次这个组件。这就是为什么调用了两次
\u handleClick
。。每次调用
componentWillMount
时,它都会向documetn对象添加一个新的单击处理程序