React原生组件中的高阶组件(HOC)和继承有什么区别

Gow*_*man 5 ecmascript-6 reactjs react-native es6-class

我是 .net 背景的新手,

这里的问题是 HOC 与 OOPS 概念中的继承有何不同,它具有具有基属性的父类和扩展 Base 并使用 Base 类中的状态、属性和基方法的子类。

在 React Components 中实现Parent->Child->GrandChild层次关系的最佳方式是什么?

例如:

Parent.js看起来像

class Parent extends Component
{
    constructor(props)
    {
        super(props);
        this.state = {
            value: "Parent",
            BaseText: "Inheritance Example"
        }
    }

    onUpdate = () => {
        console.log("Update called at Parent")
    }
}
Run Code Online (Sandbox Code Playgroud)

Child.js扩展了 Parent.js

class Child extends Parent
{
    constructor(props)
    {
        super(props);
       //this state should inherit the properties of Parent and override only the value property
        this.state = {
            value: "Child",
        }
    }

    onUpdate = () => {
        super.onUpdate();
        console.log("Update called at Child view")
    }



    render()
    {
        return(
            <View>
                <Text> Child View</Text>
            </View>
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

GrandChild.js扩展自Child.js

class GrandChild extends Child
    {
        constructor(props)
        {
            super(props);
           //this state should inherit the properties of Child, Parent and properties specific to this
            this.state = {
                value: "GrandChild",
                Name: "Test Grand Child"
            }
        }

        onUpdate = () => {
            super.onUpdate();
            console.log("Update called at Grand Child view")
        }



        render()
        {
            return(
                <View>
                    <Text> Grand Child View</Text>
                </View>
            )
        }
    }
Run Code Online (Sandbox Code Playgroud)

这是在本机反应中实现抽象的正确方法吗?比如父类将具有公共状态属性,而子类继承父类状态并拥有自己的属性。

在这种情况下如何继承状态以及如何将值更新为状态?

Est*_*ask 3

React 提倡组合作为类继承的替代方案。组件被设计为能够有效地组合。Hooks API通过以前需要使用类组件的功能来增强功能组件。

这并不意味着不允许继承。它的问题在于,React 生态系统中广泛使用的现有模式(例如高阶组件)与 OOP 不兼容:

const withBaz = Comp => <Comp baz />

@withBaz
class Bar extends Foo { ... }
Run Code Online (Sandbox Code Playgroud)

这种方法很常见,但它不适合 OOP,因为在这种情况下Bar实际上不再是一个类,而是箭头函数,它不能进一步继承。

只要开发人员控制类层次结构中的所有组件,对第一方 React 组件使用 OOP 就没有问题,但这可能不切实际,因为总是可能需要涉及不 OOP 友好的第三方代码。在合适的地方使用组合可以带来更灵活的设计。