在React.createClass

时间:2017-08-01 16:05:49

标签: javascript reactjs

我正在尝试在React.createClass函数中调用其他函数,但由于某些原因它不起作用,我得到Cannot read property 'test' of undefined

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

现在,如何从componentDidMount调用this.test()(React的内置函数)?

谢谢!

1 个答案:

答案 0 :(得分: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>
        );
    }
});
相关问题