React:无法访问getDefaultProps中的mixin函数

时间:2015-05-23 00:26:07

标签: javascript node.js reactjs mixins

我正在尝试从 getDefaultProps 访问mixin中定义的函数,但我得到undefined is not a function。基本上我使用的是react-intl,我的列的默认标签应该被翻译。为什么我无法从getDefaultProps中访问mixin中定义的函数?

var React = require('react');
var ReactIntl = require('react-intl');
var IntlMixin = ReactIntl.IntlMixin;

var Index = React.createClass({

  mixins: [IntlMixin],

  getDefaultProps: function () {
    return ({
      options: {
        attributes: [{name: 'name', label: this.getIntlMessage('Index.name'), index: 0}],
        view: "tiles"
      }
    });
  },

  render: function() {
    return <div>{this.props.options.attributes[0].label}</div>
  }
});

module.exports = Index;

1 个答案:

答案 0 :(得分:8)

无法访问它,因为getDefaultProps只被调用一次,而不是在您正在创建的类的实例的上下文中。 this上下文不正确。

您需要将检索移动到实例函数中,例如render

您还应该知道,在getDefaultProps中返回的数组或对象实例在所有实例之间共享。我不知道你是如何使用它的,但它可能会导致问题,具体取决于你如何使用这些值。

相关问题