javascript - 将组件作为普通 JS 对象进行 react ?

标签 javascript class reactjs javascript-objects ecmascript-6

是否有人有使用 React 组件作为普通 JS 对象而不是烦人的 ES6 类和已弃用的 .createClass 方法的经验。

也许您有一些工厂函数或类似函数的示例可以分享?

谢谢!

最佳答案

React.Component 是一个普通的 JavaScript 函数,因为 es6 类是围绕它们的语法糖。所以我们可以使用任何我们喜欢的 es5 类概念,例如我只是在这里借用了 Backbone 的 extend 方法:

// From backbone
var extend = function(protoProps) {
    var parent = this;
    var child;

    var extendObj = function(obj1, obj2) {
       for (var i in obj1) {
          if (obj1.hasOwnProperty(i)) {
             obj2[i] = obj1[i];
          }
       }
    };

    // The constructor function for the new subclass is either defined by you
    // (the "constructor" property in your `extend` definition), or defaulted
    // by us to simply call the parent constructor.
    if (protoProps && hasOwnProperty.call(protoProps, 'constructor')) {
      child = protoProps.constructor;
    } else {
      child = function() { return parent.apply(this, arguments); };
    }

    // Set the prototype chain to inherit from `parent`, without calling
    // `parent` constructor function.
    var Surrogate = function(){ this.constructor = child; };
    Surrogate.prototype = parent.prototype;
    child.prototype = new Surrogate;

    // Add prototype properties (instance properties) to the subclass,
    // if supplied.
    if (protoProps) extendObj(child.prototype, protoProps);

    // Set a convenience property in case the parent's prototype is needed
    // later.
    child.__super__ = parent.prototype;

    return child;
};

React.Component.extend = extend;

然后我们可以创建这样的组件:

var MyComponent = React.Component.extend({
    constructor: function() {
        console.log('hello from react component');

        this.state = {
            open: false
        };

        React.Component.apply(this, arguments);
    }
});

new MyComponent();

这只是一个示例(未经测试),您可以执行您喜欢的任何类型的原型(prototype)实现,因为它只是一个普通函数。如果您搜索“es5继承”,您应该能够应用这些解决方案中的任何一个。

关于javascript - 将组件作为普通 JS 对象进行 react ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30998161/

相关文章:

python - 为什么我的 Python 自定义数学重载类方法不起作用?

javascript - React 开发工具提示生产中的未缩小版本

reactjs - React 中副作用的定义和函数式编程中的一样吗?

javascript - 通过特定应用程序获取轨道时,标签过滤似乎不起作用

javascript - React 中如何判断哪个组件触发了事件处理器?

Javascript/jQuery : Select class name that contains word

c++ - 对 C++ 中的类::函数的 undefined reference

reactjs - Webpack 4 和 React loadable 似乎没有为服务器端渲染创建正确的 block

javascript - 如何使用 jQuery 应用嵌套的 css?

javascript - 使用 Javascript 验证验证码