本文介绍了扩展React.js组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的事情之一,我AP preciate的约Backbone.js的最古朴典雅的继承是如何工作的。我开始得到来与握把,并不能真正找到任何反应中类似这种骨干code

One of the things I appreciate the most about Backbone.js is how simple and elegant inheritance works. I'm starting to get to grips with React, and can't really find anything in react that resembles this Backbone code

var Vehicle = Backbone.View.extend({
    methodA: function() { // ... }
    methodB: function() { // ... }
    methodC: function() { // ... }
});

var Airplane = Vehicle.extend({
    methodC: function() {
        // Overwrite methodC from super
    }
});

在我们做出反应和使用这些我们可以得到一定程度接近上面的例子,如果我们去这样

In react we have mixins, and using those we could get somewhat close to the above example if we went like this

var vehicleMethods = {
    methodA: function() { // ... }
    methodB: function() { // ... }
}

var Vehicle = React.createClass({
    mixins: [vehicleMethods]
    methodC: function() {
        // Define method C for vehicle
    }
});

var Airplane = React.createClass({
    mixins: [vehicleMethods]
    methodC: function() {
        // Define method C again for airplane
    }
});

这是比一遍又一遍地定义同样的东西少重复,但它似乎并不几乎为骨干的方式灵活。举例来说,我得到一个错误,如果我尝试重新定义/覆盖存在于我的混入的一种方法。最重要的是,该React.js方式更code为我写的。

This is less repetitive than defining the same stuff over and over again, but it doesn't seem to be nearly as flexible as the Backbone way. For instance, I get an error if I try to redefine/overwrite a method that exists in one of my mixins. On top of that, the React.js way is more code for me to write.

有在某些反应令人难以置信的聪明的东西,感觉这更是我没有得到如何正确地做到这一点的情况下,比感觉就像一个从功能缺失做出反应。

There is some incredibly clever stuff in react, and it feels like this is more the case of me not getting how to properly do this, than it feels like a feature missing from React.

任何指针是极大的AP preciated。

Any pointers are greatly appreciated.

推荐答案

要得到的东西,类似于继承(实际上是组成的在评论中指出),可以使一个飞机在你的榜样本身包裹在。如果你想露出车辆方法飞机组件,你可以使用的以及连接它们一个接一个。这不正是继承(它实际上的组成的),特别是因为 this.refs.vehicle 将无法访问后才组件已安装

To get something that resembles inheritance (actually composition as pointed out in comments), you can make an Airplane in your example wrap itself in a Vehicle. If you want to expose methods on Vehicle in the Airplane component, you can use a ref and connect them one-by-one. This is not exactly inheritance (it's actually composition), particularly because the this.refs.vehicle will not be accessible until after the component has been mounted.

var Vehicle = React.createClass({
    ...
});

var Airplane = React.createClass({
    methodA: function() {
      if (this.refs != null) return this.refs.vehicle.methodA();
    },
    ...
    render: function() {
        return (
            <Vehicle ref="vehicle">
                <h1>J/K I'm an airplane</h1>
            </Vehicle>
        );
    }
});

这篇关于扩展React.js组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 17:11