【发布时间】:2019-04-12 18:08:27
【问题描述】:
我是 .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>
)
}
}
这是在 react native 中实现 抽象 的正确方法吗 说父类将具有公共状态属性,子类继承父状态并具有自己的属性。
在这种情况下如何继承状态以及如何将值更新为状态。?
【问题讨论】:
-
HOC 使用组合,reactjs.org/docs/composition-vs-inheritance.html。这一点类似于 OOP 的 en.wikipedia.org/wiki/Composition_over_inheritance 。 这是实现 Parent-> Child -> GrandChild 层次关系的最佳方式 - 没有“最佳方式”,因为这取决于组件。如果您有特定的案例,请考虑使用特定的代码示例重新提出问题。
-
肯定会用示例代码sn-p修改问题。
-
你有更真实的例子吗?
this.state子组件中的继承不适用于组件组合,但我想不出这样做的好理由。如果状态变得如此复杂,则可能需要使用状态管理(Redux?)。组件需要重构以更好地适应组合,但我不能建议如何做到这一点,因为不清楚组件的真正作用。顺便说一句,onUpdate不适合继承,因为它是实例方法,不会有super.onUpdate,它应该是原型方法。 -
JavaScript 中的继承是原型。 HOC 是组合函数。
标签: reactjs react-native ecmascript-6 es6-class