通过“;类“"实例”;使用ReactJS组件代替“props”文字

passing "class" "instances" to ReactJS components in lieu of `props` literals

本文关键字:组件 props 文字 ReactJS 使用 quot 实例 通过      更新时间:2023-10-02

当涉及到React.createElement中提供的props对象时,createElement方法似乎只检查该对象的可枚举属性(或者至少看起来是这样)。

因此,如果我使用ECMAScript-6类对我的ReactJS状态进行建模,该类带有更改该状态的方法(封装,对吧?),我就不能在对createElement的调用中将该状态传递给ReactJS组件,因为ReactJS看不到这些方法。所以我必须这样做:

const MyApp = React.createClass({
      propTypes: {
          methodA: React.PropTypes.func.isRequired,
          methodB: React.PropTypes.func.isRequired
      },
...});
class MyAppState {
...
}
let appState = new MyAppState();
ReactDOM.render(
    React.createElement(MyApp, Object.assign(
         {
          methodA: s.methodA.bind(s),
          methodB: s.methodB.bind(s)
         }, appState))
    , document.getElementById('somePlace')
)

这有点违背目的。我不是Javascript"类"的铁杆粉丝,但有没有一种方法可以让类以这种方式为ReactJS元素提供props?类"字段"是可枚举的,所以没有问题,因为我不能通过这种方式传递方法/操作。

您遇到的问题是,您的方法没有在类实例上定义,它们是在构造函数的原型上定义的。

当React迭代类实例时,它不会迭代原型上的成员。

将应用程序状态建模为常规对象更简单,您可能会发现这种方法使应用程序更具可预测性。

使用对象还可以序列化状态以保存和读取为JSON(没有办法序列化类)。

如果使用类是因为需要创建多个状态实例,那么可以使用工厂函数。

function makeAppState(foo, bar, baz) {
  return {
    qux: foo + bar - baz
  };
}

如果你使用一个类是因为你想用一些方法直接操纵你的状态,那么你也可以用工厂函数和原型来实现这一点。

function makeAppState(foo, bar, baz) {
  var state = Object.create(AppStatePrototype);
  state.qux = foo + bar - baz;
  return state;
}
var AppStatePrototype = {
  update() {
    this.qux = 0;
  }
};

至少在这种情况下,我更清楚update方法不会出现在从makeAppState返回的对象上。

如果您想将方法和属性一起传递,只需返回一个同时包含这两个方法和属性的对象文字即可。

function makeAppState(foo, bar, baz) {
  return {
    qux: foo + bar - baz,
    update() {
      this.qux = 0;
    }
  };
}