英文:
React extends for function component?
问题
我有一个类组件,它继承自另一个类组件:
export default class MyLittleComponent extends TheBigBoy
现在我需要将MyLittleComponent
重构为函数组件,以便它可以与钩子等一起使用。但这样一来,我将失去从TheBigBoy
继承的一切内容。
是否有一种方法可以编写函数组件并保留对TheBigBoy
的依赖/扩展?
TheBigBoy
在整个应用程序中都在使用,所以我不能立即将其删除。
我可以可能创建TheBigBoy
的函数副本,然后以某种方式将其附加到MyLittleComponent
,但在我所知道的范围内,函数组件没有类似于“extends”的东西。有没有某种钩子或其他方式?我想避免使用高阶组件,因为那是我想要避免的事情之一。
英文:
I have a class component that extends another class component:
export default class MyLittleComponent extends TheBigBoy
Now I need to refactor MyLittleComponent
to functional component so it works with hooks etc. But then I lose everything inherited from TheBigBoy
.
Is there a way to write function component AND to keep the dependency/extension of TheBigBoy
?
TheBigBoy
is used all over the app so I can't remove it just yet.
I can possibly make a function copy of TheBigBoy
and then somehow attach it to MyLittleComponent
but what would be the best way as there's no "extends" for function components as far as I know? A hook of some sort? I want to avoid HOC as that's one of the things I'm running away from.
答案1
得分: 1
总的来说,React团队建议组合优于继承。
不过,你可以采用双管齐下的方法:
- 将逻辑和状态管理从
TheBigBoy
移动到一个自定义钩子中。然后,你的MyLittleComponent
可以使用该钩子。 - 将
TheBigBoy
转换为一个接受子组件的组件。然后,你可以将你的MyLittleComponent
传递给TheBigBoy
。
希望对你有所帮助。
英文:
In general, React team recommends composition over inheritance.
What you can do though, is to use a two-pronged approach:
- Move the logic and state management from
TheBigBoy
to a custom hook. Then yourMyLittleComponent
can use that hook. - Turn
TheBigBoy
into a component that takes children. You can then pass yourMyLittleComponent
intoTheBigBoy
Hope that helps.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论