2017-08-01 35 views
1

我試圖打電話等功能於React.createClass功能,但它並不適用於某些原因,我越來越Cannot read property 'test' of undefined調用等功能於React.createClass

var WallFeed = React.createClass({ 
    test:() => { 
     console.log('hello world'); 
    }, 
    componentDidMount:() => { 
     this.test(); 
    }, 
    render:() => { 
     return (
      <div>test</div> 
     ); 
    } 
}); 

現在,我怎麼能從componentDidMount(React的內置函數)調用this.test()?

謝謝!

+1

你爲什麼不使用如說是消除對React.createClass支持發展反應的反應社會ES6類? –

回答

2

請勿在傳遞到createClass的對象字面量中使用箭頭函數。對象文字中的箭頭函數將始終使用window作爲this來調用。一個解釋見Arrow Function in object literal

var WallFeed = React.createClass({ 
    test() { 
     console.log('hello world'); 
    }, 
    componentDidMount() { 
     this.test(); 
    }, 
    render() { 
     return (
      <div>test</div> 
     ); 
    } 
}); 
+1

這個問題與React自動綁定方法無關。自動綁定對於用作事件處理程序的方法很有用,但沒有一個方法用作事件處理程序。 –

+0

@FelixKling阿哈好點,謝謝指出。我會從答案中刪除提及的自動綁定。 –