简体   繁体   English

装饰器或子类是React.Component的最佳模式

[英]Decorators or subclassing is best pattern for React.Component

Which is the recommended way and why? 推荐哪种方法,为什么?

way_1:(Using inheritance) 方式_1 :(使用继承)

class BaseComponent extends React.Component {

    //Other functions

    log = (msg) => {
        console.log(`[${this.constructor.name}]`, msg);
    }

    //Other functions
}

export default BaseComponent;


class XyzComponent extends BaseComponent {

    //Other functions

    someFunction = () => {
        this.log("Some log");
    }

    //Other functions
}

export default XyzComponent;

way_2:(Using decorators) way_2 :(使用装饰器)

function withLog(ComposedComponent) {
    return class withLog extends Component {
        log = (msg) => {
            console.log(`[${this.constructor.name}]`, msg);
        }
    }
};

export default withLog;

@withLog
class XyzComponent extends React.Component {

    //Other functions

    someFunction = () => {
        this.log("Some log");
    }

    //Other functions
}

I liked way_1 because it looks like other OOPs based languages. 我喜欢way_1,因为它看起来像其他基于OOP的语言。 Which makes constancy and easier to understand. 这使得稳定性和易于理解。 But everywhere else people saying about decorators. 但是在其他任何地方,人们都在谈论装饰。 So I'm bit confused. 所以我有点困惑。

People likely reccomend decorators because they internalize the functionality you want. 人们可能会推荐装饰器,因为它们内部化了您想要的功能。

When you inherit from BaseComponent in your first example you're creating a strong (inheritence) dependency between XyzComponent and BaseComponent . 在第一个示例中从BaseComponent继承时,您正在XyzComponentBaseComponent之间创建强(继承)依赖性。 Then, any changes to BaseComponent may have an indirect effect on XyzComponent s. 然后,对BaseComponent任何更改可能会对XyzComponent产生间接影响。

A more likely scenario is if--later down the line--you decide to change XyzComponent 's logging method. 更有可能的情况是,如果您决定(稍后)决定更改XyzComponent的日志记录方法。 If you took the first approach it might be difficult to "cut out the middle" and inherit from React.Component because other parts of your codebase might be accessing XyzComponent through its BaseComponent superclass. 如果您采用第一种方法,则可能很难“切出中间层”并从React.Component继承,因为代码库的其他部分可能XyzComponent通过其BaseComponent超类访问XyzComponent In that case, you'd have to ensure that your modifications don't violate BaseComponent 's contract. 在这种情况下,您必须确保所做的修改不会违反BaseComponent的合同。

So, although the inheritence approach is easy to grasp and very OO it might cause headaches later. 因此,尽管继承方法很容易掌握且非常面向对象,但以后可能会引起头痛。 If you're aware of those headaches make a judgement call - I personally find inheritence to be self-explanatory wheras the decorators are a little more indirect. 如果您知道这些头痛的问题,请做出判断-我个人认为继承是不言而喻的,装饰者是间接的。

(This answer can be summed up as: "Prefer composition over inheritence") (这个答案可以总结为:“优先考虑组成而不是继承”)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM