javascript - react : cannot access mixin function inside getDefaultProps

标签 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;

最佳答案

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

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

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

关于javascript - react : cannot access mixin function inside getDefaultProps,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30407642/

相关文章:

javascript - solr 正在为我的本地 iis 工作,而不是为托管 iis 工作

node.js - 将在任何路由上执行的自定义中间件

node.js - 当没有消费者时获取消息以保留在 RabbitMQ 中

node.js - Docker Node Alpine 镜像构建在 node-gyp 上失败

css - React 和 MUI - 我的点击按钮动画没有像我想要的那样工作

reactjs - Redux 状态应该如何剖析?

css - 图片不显示在 React JS 轮播 slider 中

javascript - 如何获取 JSON 中的 URL 并将其放入模式中?

javascript - Polymer ready() 和事件监听器

javascript - 使 DOM 的 JavaScript 函数可链接