2016-02-11 31 views
2

在我的應用程序,我使用的componentDidMound第三方插件,東西會看起來像這樣的:讓jQuery對象反應componentDidMount

clickStuff: function() { 
    //do stuff 
}, 
componentDidMount: function() { 

    $(".whatever").on { 'click', function() { 
     this.clickStuff(); 
    }.bind(this)); 
} 

這使得它在哪裏,如果我點擊類別爲「任何」的任何div以進入反應函數「clickStuff()」;

但是如果我想獲得「本」 jQuery的節點。像$(「。whatever」)的屬性一樣?例如:

componentDidMount: function() { 

    $(".whatever").on { 'click', function() { 
     //this will cause conflict between the two this 
     $(this).attr("title", this.state.titleMessage); 
    }.bind(this)); 
} 

如果這$(這)應該是jQuery的節點,這在「this.state.titleMessage」應該是反應的一部分。

你如何既要相同功能的一部分?還是我需要做一些奇特的事情?我對如何做到這一點感到困惑。我不知道該怎麼稱呼這個問題。

+0

以避免與其他API的任何衝突,你可以做的jQuery(this)來獲得jQuery對象。 – DinoMyte

+0

我明白你的意思了。一個是jQuery對象。你可以試試$(this)[0]來獲得節點。 – Casey

+0

獲取jquery對象很好,我認爲對他來說吧?他只需要該節點的實例,與document.getElementById(id)相同;除非我不正確。 – Casey

回答

1

老辦法:

componentDidMount: function() { 
    var that = this; 
    $(".whatever").on { 'click', function() { 
     //that is the this of componentDidMount (and so of clickStuff) 
     that.clickStuff(); 
     //this remains the same 
     $(this).attr("title", that.state.titleMessage); 
    }); 
} 
+0

我以前就是這樣做的,而且它在工作。我想這是最好的解決方案,使用綁定: -/ – sksallaj

+0

JavaScript是一種棘手的語言,記住了「新方法」(綁定是不是太新了,雖然)和舊的方式;-) – topheman

+0

葉,它有點臭,因爲新方法顯示在反應教程中。 – sksallaj