简体   繁体   English

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

[英]React: cannot access mixin function inside getDefaultProps

I'm trying to access a function defined in a mixin from getDefaultProps but I get undefined is not a function . 我正在尝试从getDefaultProps访问一个在mixin中定义的函数,但undefined is not a function Basically I'm using react-intl and the default label of my column should be translated. 基本上,我正在使用react-intl并且应该翻译我列的默认标签。 Why I can't access functions defined in the mixin from within getDefaultProps? 为什么我不能从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;

It can't be accessed because getDefaultProps is just called once and not in the context of an instance of the class you're creating. 无法访问它,因为getDefaultProps仅被调用一次,而不是在您正在创建的类的实例的上下文中。 The this context isn't correct. this情况是不正确的。

You'll need to move the retrieval into an instance function, like render . 您需要将检索结果移至实例函数,如render

You also should be aware that an array or object instance when returned in getDefaultProps is shared across all instances. 您还应该注意,在getDefaultProps返回的数组或对象实例在所有实例之间都是共享的。 I don't know how you're using it, but it could cause a problem depending on how you use the values. 我不知道您如何使用它,但这可能会导致问题,具体取决于您使用值的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM