React:无法访问 getDefaultProps 中的 mixin 函数
React: cannot access mixin function inside getDefaultProps
我试图从 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
仅被调用一次,而不是在您正在创建的 class 实例的上下文中。 this
上下文不正确。
您需要将检索移动到实例函数中,例如 render
。
您还应注意,在 getDefaultProps
中返回的数组或对象实例在所有实例之间共享。我不知道你是如何使用它的,但它可能会导致问题,具体取决于你如何使用这些值。
我试图从 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
仅被调用一次,而不是在您正在创建的 class 实例的上下文中。 this
上下文不正确。
您需要将检索移动到实例函数中,例如 render
。
您还应注意,在 getDefaultProps
中返回的数组或对象实例在所有实例之间共享。我不知道你是如何使用它的,但它可能会导致问题,具体取决于你如何使用这些值。