【问题标题】:React extends class using ES5React 使用 ES5 扩展类
【发布时间】:2015-09-09 22:28:42
【问题描述】:

这是 ES6 语法,对我来说没问题:

import {Component} from 'react';
class A extends Component {}
class B extends A {
    // I can redeclare some methods here
}

以及如何用 ES5 实现这一点?我的意思是:

var React = require('react');
var A = React.createClass({});
var B = ???

有人可以举个例子吗?

【问题讨论】:

  • 你的意思是class B extends A
  • 是的,抱歉,我刚刚修正了这个错字
  • 最简单的方法是在 npm 上使用 inherits 模块,我从来没有在 es5 中这样做过并做出反应,所以你必须自己尝试一下。
  • createClass 是一个完全独立的接口。如果您只想在没有 ES6 的情况下从 Component 继承,请使用 inherits 或像许多教程中解释的那样手动设置原型。如果你想使用createClass,你会遇到麻烦,因为它不是为此而设计的。你要哪个?

标签: javascript class inheritance reactjs


【解决方案1】:

我的代码

React.extend=function(parentClass,nprototype){
    var childClass=function(){};
    childClass.prototype=new parentClass({});
    for(var i in nprototype){
        childClass.prototype[i]=nprototype[i];
    }
    return childClass;
}

var Parent=React.createClass({
    getContent:function(){

    },
    render:function(){
        return (
            <div>{this.getContent()}</div>
        );
    }
});

var Child=React.extend(Parent,{
    getContent:function(){
        return "this is child Content";
    }
});
猜你喜欢
  • 2018-11-28
  • 2019-11-18
  • 1970-01-01
  • 2018-06-29
  • 2021-08-18
  • 1970-01-01
  • 2017-04-27
  • 1970-01-01
  • 2016-01-31
相关资源
最近更新 更多