React:在 mixin 代码 运行 之前让组件接收 props 或 state,或者生成一个 id

React: have component receive props or state, or generate an id, before mixin code is run

在我的 React 组件中,我希望能够向 mixin 传递一个动态值,该值可以从组件的 props 或状态接收,也可以从组件 运行 在执行混合。这可能吗?

基本上,我想按照以下方式做一些事情:

/** @jsx React.DOM */
var React = require('react');
var MyMixin = require('./myMixin').MyMixin;

var Test = React.createClass({
  mixins: [MyMixin.wantsToKnowTheTestId(this.props.id)],
  propTypes: {
    id: React.PropTypes.string.isRequired
  },
  render: function() {
    return (<h1>My id is: {this.props.id}</h1>);
  }
});

module.exports = {Test: Test};

当然,当我 运行 以上时,我得到 Uncaught TypeError: Cannot read property 'id' of undefined 因为 this.props 还没有定义,当 mixin 运行s.

这或类似的东西可能吗?

您可以将 mixin 中的代码视为简单地复制到您的组件中,因此您的想法是行不通的。

根据您的 mixin 中的方法在做什么,您可以考虑在您的 mixin 中使用生命周期方法,该方法将在组件初始化后执行(因此一旦 this.props 被定义)。

所以你的 mixin 看起来像

var MyMixin = {
  wantsToKnowTheTestId: function(id) { ... },

  componentDidMount: function() {
    this.wantsToKnowTheTestId(this.props.id);
  }

}

你的组件将简单地包含这个 mixin

/** @jsx React.DOM */
var React = require('react');
var MyMixin = require('./myMixin').MyMixin;

var Test = React.createClass({
  mixins: [MyMixin],
  propTypes: {
    id: React.PropTypes.string.isRequired
  },
  render: function() {
    return (<h1>My id is: {this.props.id}</h1>);
  }
});

module.exports = {Test: Test};