2017-03-07 10 views
1

如果您在jsx中綁定(this)是正確的,那麼在構造函數中使用bind是可選的?無法讀取綁定的屬性這是沒有在響應中定義

render(){ 
    return(
     <input onChange={this.myFunc.bind(this)} type="text"/> 
    ) 
} 

myFunc(){ 
    alert('should trigger'); 
} 

但是我得到了無法讀取綁定此錯誤屬性的錯誤。這裏是我的全JS文件http://pastebin.com/yL7BtN8h

+0

做'this.myFunc.bind(這)' – Li357

+0

你的引擎收錄鏈接不起作用。請在此發佈*全部*相關代碼,而不是在其他網站上發佈。 –

回答

0
<input onChange={this.myFunc.bind(this)} type="text"/> 

而不是:

<input onChange={myFunc.bind(this)} type="text"/> 
+0

我在我的文件中做到了這一點,http://pastebin.com/yL7BtN8h但仍然有錯誤。 –

0

Abdennour在技術上是正確的,但結合每次調用.render(時間同樣的方法)比在構造函數結合,一旦效率低。許多開發人員認爲這種方法最佳實踐:

class MyComponent extends React.Component { 
    constructor() { 
     super(); 

     this.myFunc = this.myFunc.bind(this); 
    } 

    myFunc(){ 
     alert('should trigger'); 
    } 

    render() { 
     return(
      <input onChange={this.myFunc} type="text"/> 
     ); 
    } 
} 
相關問題