React函数组件的扩展?

huangapple go评论68阅读模式
英文:

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团队建议组合优于继承

不过,你可以采用双管齐下的方法:

  1. 将逻辑和状态管理从 TheBigBoy 移动到一个自定义钩子中。然后,你的 MyLittleComponent 可以使用该钩子。
  2. TheBigBoy 转换为一个接受子组件的组件。然后,你可以将你的 MyLittleComponent 传递给 TheBigBoy

希望对你有所帮助。

英文:

In general, React team recommends composition over inheritance.

What you can do though, is to use a two-pronged approach:

  1. Move the logic and state management from TheBigBoy to a custom hook. Then your MyLittleComponent can use that hook.
  2. Turn TheBigBoy into a component that takes children. You can then pass your MyLittleComponent into TheBigBoy

Hope that helps.

huangapple
  • 本文由 发表于 2023年6月26日 07:55:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76552850.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定