2017-04-21 60 views
0

我只是想知道爲什麼render()默認將'this'設置爲'正確'或直觀的值,但隨後我在組件上定義的任何其他方法必須明確設置'this'。爲什麼我的組件的render()方法是唯一默認具有正確值'this'的方法?

例如:

class App extends React.Component { 

    constructor (props) { 
     super(props); 
    } 

    onFormSubmit (e) { 
     e.preventDefault(); 
     console.log(this); 
    } 

    render() { 

     console.log(this); 

     return (
     <div> 
      <form onSubmit={this.onFormSubmit}> 
      <input type="search"/> 
      <button>Submit</button> 
      </form> 
     </div> 
    ); 
    } 

    } 

    ReactDOM.render(
    <App/>, 
    document.getElementById('app') 
); 

上述控制檯輸出是

App {props: Object, context: Object...} 
null 

爲什麼呢?有沒有什麼方法可以使this默認在兩種情況下都是指App?或者我只需要在constructor中繼續寫this.onFormSubmit = this.onFormSubmit.bind(this);

也許這是沒有意義的想用默認這種行爲(我很新的節目!),但如果是這樣的話請解釋爲什麼:)

所有最優秀的

[編輯]另外...爲什麼在onFormSubmit函數中引用this時返回null

+0

因爲其它功能用於轉換數據..和過渡是異步 –

+1

的'值this'取決於函數是如何被調用。不是它是如何定義的。參見:http://stackoverflow.com/questions/13441307/how-does-the-this-keyword-in-javascript-act-within-an-object-literal/13441628?s=1|4.2098#13441628 – slebetman

回答

0

爲了以防萬一,你試過<form onSubmit={this.onFormSubmit.bind(this)}>

this返回null,因爲你只是調用組件App定義的方法.onFormSubmit()(由你的第一個執行console.log返回: 應該沒有構造


內結合對於編輯工作線)沒有任何上下文。

我邀請你來檢查這個ressources:

  • 爲了瞭解.bind/.CALL /。適用方法

http://javascriptissexy.com/javascript-apply-call-and-bind-methods-are-essential-for-javascript-professionals/

  • 一個很好的教程陣營基礎,在這段視頻中,他解釋了爲什麼你應該總是使用.bind()來避免這些問題的背景

https://www.youtube.com/watch?v=_D1JGNidMr4&index=5&list=PLoYCgNOIyGABj2GQSlDRjgvXtqfDxKm5b

+1

Manu,感謝您的這些鏈接。那篇關於bind(),call()和apply()方法的文章特別有用,在那個網站上也有一篇關於'this'的文章,這有助於。我認爲我學到的是'this'指的是調用'this'被引用的函數的對象。 – NoobOfNoobs

+0

是的,因爲當你調用objectA中定義的方法時,用不同的上下文(從objectB)處理它的唯一方法是綁定或調用objectB的'this'上下文! 像'var a = {name:「Manu」,showName:()=> {return this。}} //// 'var b = {name:「user3624937」}'//// 'a.showName.bind(b)'將返回「user3624937」 – Manu

+0

非常好,非常感謝您很多 - 這有幫助! – NoobOfNoobs

相關問題