【问题标题】:calling other functions in React.createClass [duplicate]在 React.createClass 中调用其他函数 [重复]
【发布时间】:2018-01-08 14:34:00
【问题描述】:

我正在尝试调用 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(React 的内置函数)调用 this.test()?

谢谢!

【问题讨论】:

  • 为什么不使用 es6 类进行 React 开发作为 React 社区,据说要删除对 React.createClass 的支持?

标签: javascript reactjs


【解决方案1】:

不要在传递给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>
        );
    }
});

【讨论】:

  • 手头的问题与 React 自动绑定方法无关。自动绑定对于用作事件处理程序的方法很有用,但没有一个方法用作事件处理程序。
  • @FelixKling 好点,感谢您指出这一点。我将从答案中删除对自动绑定的提及。
猜你喜欢
  • 1970-01-01
  • 2021-04-06
  • 2022-11-15
  • 2018-06-09
  • 1970-01-01
  • 2018-10-17
  • 2020-12-15
  • 1970-01-01
相关资源
最近更新 更多