2015-10-07 36 views
1

我知道如何讓父函數在onClick事件(或類似的事件)上觸發時運行,但我想在ajax成功時觸發它。因此,相當多這樣constallation:在ajax上觸發父函數reactjs

var parent = React.createClass({ 
    someFunction: function(){ 
     console.log("Parent function triggered"); 
    }, 
    render: function(){ 
     return (
      <Child callback={this.someFunction} /> 
     ); 
    } 
}); 

var child = React.createClass({ 
    getInitialState: function(){ 
     return { data: "Wat" }; 
    }, 
    componentDidMount: function(){ 
     $.ajax({ 
      url: "some_url", 
      method: 'POST', 
      data: this.state.data, 
      success: function(response){ 
       this.props.callback; // This is what I would like to do 
      }, 
      error: function(){ 
       console.log("Couldn't do it cap'n"); 
      } 
     }); 
    }, 
    render: function(){ 
     return(
      <div>Hello!</div> 
     ); 
    } 
}); 

我可以觸發事件做到這一點,但肯定應該能夠做到這一點,當我訪問該功能。該功能也被傳遞下來正確的,我可以把它看作一個函數,如果我做了console.log(this.props.callback);

+1

你有什麼完成是非常正確的。您只需要以這種方式執行該函數 - this.props.callback()。更改函數的this關鍵字,或者直接聲明var that = this,並調用that.props.callback() – booleanhunter

回答

4

您應該使用Function.prototype.bind改變功能的this關鍵字:

success: function(response){ 
    this.props.callback(); // This will work 
}.bind(this), 

原來,裏面的this關鍵字匿名功能,因爲success選項到ajax方法與this不一樣。

發生這種情況是因爲Javascript的詞法範圍,您可以通過覆蓋調用該函數時關鍵字this的內容來更改此行爲。


另一種方法是使用一個輔助變量,如:

componentDidMount: function() { 
    var self = this; 
    $.ajax({ 
    /* (...) */ 
    success: function(response) { 
     self.props.callback(); // this will work as well 
    }, 
    /* (...) */ 
    }); 
} 

還有一個選擇是Kevin B的建議,使用jQuery的AJAX context選項:

componentDidMount: function() { 
    $.ajax({ 
    /* (...) */ 
    context: this, 
    success: function(response) { 
     this.props.callback(); // this will work as well 
    }, 
    /* (...) */ 
    }); 
} 

和最後的選擇,因爲你使用的反應,你可能transpiling通過通天你的代碼,所以,你可以採取ES6's arrow functions的優勢,將自動詞法的this結合:

success: (response) => { 
    this.props.callback(); // This will work too 
}, 
+0

!!您需要執行'self.props.callback()'(帶圓括號),否則回調將不會執行。 – wintvelt

+0

只需使用箭頭函數:'success:()=> this.props.callback()'。 –

+0

@KevinB更新了我的答案,以包含您的建議 – Buzinas