Reactjs 子类化react组件,HOC还是经典OO?

Reactjs 子类化react组件,HOC还是经典OO?,reactjs,components,subclassing,Reactjs,Components,Subclassing,我正在编写一个React应用程序,负责从外部CMS呈现内容 当应用程序首次加载时,内容从CMS拉入redux存储,并在其整个生命周期内通过连接的组件或道具访问 我需要使用CMS的内容在所有组件中提供某些方法 在研究了实现这一点的“反应”方式后,似乎普遍不赞成以下方式,而使用高阶组件则被视为更好的做法。来自OO背景,我很难理解为什么 例如 import React, { Component } from 'react'; class CMSComponent extends Component

我正在编写一个React应用程序,负责从外部CMS呈现内容

当应用程序首次加载时,内容从CMS拉入redux存储,并在其整个生命周期内通过连接的组件或道具访问

我需要使用CMS的内容在所有组件中提供某些方法

在研究了实现这一点的“反应”方式后,似乎普遍不赞成以下方式,而使用高阶组件则被视为更好的做法。来自OO背景,我很难理解为什么

例如

import React, { Component } from 'react';

class CMSComponent extends Component {

    constructor(props) {
        super(props);       
    }

    mySharedMethod(path) {
        // Assume CMS content is located in this.props.content unless otherwise stated
        // Please be aware that the actual code has been simplified massively for the sake of the question

        return this.props.content[path]
    }
}
我现在有了一个基类,我所有的CMS组件都可以从中继承,就像这样

import CMSComponent from './components/cms'

class Page1 extends CMSComponent {

    constructor(props) {
        super(props);       
    }

    render() {

        // mySharedMethod() inherited from base class

        return <div>{ this.mySharedMethod(['data', 'intl', 'my-keyed-content']) }</div>
    }
}
从“./components/cms”导入CMSComponent
类Page1扩展了CMSComponent{
建造师(道具){
超级(道具);
}
render(){
//mySharedMethod()继承自基类
返回{this.mySharedMethod(['data','intl','my keyed content'])}
}
}
如果有人能解释为什么这被认为是不正确的,我将不胜感激

作为参考,我猜使用HOC的相同场景看起来会像这样

import React, { Component } from 'react'

export default function CMSInject(ChildComponent) {

    class CMSComponent extends Component {

        constructor(props) {
            super(props);       
        }

        mySharedMethod(path) {
            return this.props.content[path]
        }

        render() {

            return <ChildComponent {...this.props} {...this.state} /* and some refs */ />
        }
    }

    return CMSComponent
}
import React,{Component}来自“React”
导出默认函数CMSInject(ChildComponent){
类CMSComponent扩展了组件{
建造师(道具){
超级(道具);
}
mySharedMethod(路径){
返回此.props.content[路径]
}
render(){
返回
}
}
返回CMS组件
}
…然后通过高阶父组件导出子组件

import React, { Component } from 'react'

class Page1 extends Component {

    constructor(props) {
        super(props);       
    }

    render() {

        // mySharedMethod() still inherited from base HOC class

        return <div>/* CMS BASED CONENT HERE */</div>
    }
}

export default CMSInject(Page1)
import React,{Component}来自“React”
类Page1扩展组件{
建造师(道具){
超级(道具);
}
render(){
//mySharedMethod()仍然从基类继承
return/*此处基于CMS的内容*/
}
}
导出默认CMSInject(第1页)