React本机组件中的高阶组件(HOC)和继承之间有什么区别

时间:2018-11-09 07:04:37

标签: reactjs react-native ecmascript-6 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")
    }
}

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>
        )
    }
}

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>
            )
        }
    }

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

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

1 个答案:

答案 0 :(得分:1)

React促进composition作为类继承的替代方法。组件被设计为有效组成。 Hooks API使用以前需要使用的类组件的功能来增强功能组件。

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

const withBaz = Comp => <Comp baz />

@withBaz
class Bar extends Foo { ... }

这种方法很常见,但不友好,因为在这种情况下,Bar实际上不再是类,而是箭头函数,无法进一步继承。

只要开发人员控制类层次结构中的所有组件,将OOP用于第一方React组件就不会有问题,但这可能是不切实际的,因为始终需要涉及并非第三方的代码OOP友好。在合适的位置使用组合物可以使设计更加灵活。