2015-02-11 34 views
1

我有一個基本的彈出窗口(圖像),當你點擊一個按鈕時出現。當您在彈出窗口外單擊時,它應該關閉,但是當您單擊它時,它應該保持打開並調用測試功能。它的初始狀態isPopupVisible被設置爲false。當你點擊按鈕時,我將狀態設置爲true,呈現彈出窗口。反應組件onClick處理程序不工作

問題是當你點擊圖像時測試函數沒有被調用。我認爲這是因爲狀態設置爲false,並且帶有onClick函數的圖像元素最初不會被渲染。有誰知道如何解決這個問題?

(寫在ECMAScript中6)

getInitialState() { 
    return {isPopupVisible: false} 
}, 
onClick() { 
    if(!this.state.isPopupVisible){ 
    this.setState({isPopupVisible: true}); 
    document.body.addEventListener('click', this.onClickBody) 
    } 
}, 
onClickBody() { 
    this.setState({isPopupVisible: false}); 
    document.body.removeEventListener('click', this.onClickBody) 
}, 
test() { 
    console.log('the onClick from the image works!'); 
}, 
showPopup() { 
    if(this.state.isPopupVisible){ 
    return <div> 
     <img src='img.png' onClick={this.test} /> 
    </div> 
    }else{ 
    return null; 
    } 
}, 
render() { 
    return (
    <span> 
     <button onClick={this.onClick}> 
     See Popup 
     </button> 
     {this.showPopup()} 
    </span> 
); 
} 
+0

不要點擊之前clickkng或當你在控制檯中的任何錯誤? – 2015-02-11 07:22:15

+0

加載頁面或單擊圖像時不會出現錯誤。爲了測試它,我使this.state.isPopupVisible爲true,並且onClick工作。我只是無法弄清楚爲什麼最初不渲染時它不起作用。 – Donielle 2015-02-11 07:30:48

回答

0

這是一個黑客位的,但是......

onClickBody() { 
    setTimeout(function(){ 
    if (!this.clickedInBounds && this.isMounted()) { 
     this.setState({isPopupVisible: false}); 
     document.body.removeEventListener('click', this.onClickBody) 
    } 
    this.clickedInBounds = false;  
    }.bind(this), 0); 
}, 
test() { 
    console.log('the onClick from the image works!'); 
    this.clickedInBounds = true; 
}, 

的setTimeout的只是讓它運行代碼test有後運行的機會。 isMounted僅僅是組件在點擊正文和setTimeout出現之間卸載的一個小機會。

jsbin

+0

非常感謝,@FakeRainBrigand!這有點冒險,但這是我迄今爲止唯一的工作。感謝你的幫助 :) – Donielle 2015-02-11 17:50:49

0

onClickBody處理程序得到test之前稱爲是不斷調用,改變狀態,並從虛擬DOM移除圖像合成事件以往任何時候都觸發。

可能有一個優雅的解決方法,但是因爲您混合了原生和React事件API,我的猜測是您必須更改onClickBody的簽名才能將事件作爲其第一個參數,然後包裝該方法的身體像if (e.target.nodeName !== "IMG") {}

的jsfiddle這裏顯示這個動作:http://jsfiddle.net/reactjs/69z2wepo/

0

我知道它已經過了一年的這個職位,但我知道正確答案。

你有很多參考危險。

onClick() { 
    var self = this; 
    if(!this.state.isPopupVisible){ 
    self .setState({isPopupVisible: true}); 
    document.body.addEventListener('click', self .onClickBody) 
    } 
}, 
onClickBody() { 
    var self = this; 
    this.setState({isPopupVisible: false}); 
    document.body.removeEventListener('click', self .onClickBody) 
}, 
test() { 
    console.log('the onClick from the image works!'); 
}, 
showPopup() { 
    var self = this; 
    if(this.state.isPopupVisible){ 
    return <div> 
     <img src='img.png' onClick={self.test} /> 
    </div> 
    }else{ 
    return null; 
    } 
}, 

這應該肯定的解決您的問題