2017-08-01 40 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阿哈好点,谢谢指出。我会从答案中删除提及的自动绑定。 –