简体   繁体   中英

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 . Basically I'm using react-intl and the default label of my column should be translated. Why I can't access functions defined in the mixin from within getDefaultProps?

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. The this context isn't correct.

You'll need to move the retrieval into an instance function, like render .

You also should be aware that an array or object instance when returned in getDefaultProps is shared across all instances. I don't know how you're using it, but it could cause a problem depending on how you use the values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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