2016-02-11 81 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