简体   繁体   English

创建一个组件,它是两个组件的“混合”(从2个组件扩展)

[英]Creating a component that is the “mix” of two components (extending from 2 components)

I'm building a set of components which can have variants in their behavior. 我正在构建一组组件,这些组件的行为可能有所不同。

More specific, I have a x-tag component, which can behave as a <span> that simply renders text or an <a> that also renders text and links to another route. 更具体地说,我有一个x-tag组件,它可以充当<span> (仅呈现文本)或<a> (也呈现文本并链接到另一条路线)。

For the "link" part I'm using the link component provided by Ember (which is the link-to ) to not reimplement all the routing logic by myself. 对于“链接”部分,我使用的是Ember提供的链接组件 (这是link-to ),而不是自己重新实现所有路由逻辑。

The ideal would be to only have two components: 理想的情况是只包含两个组件:

  • x-tag , simple text version that handles the base logic. x-tag是处理基本逻辑的简单文本版本。
  • x-tag-link-to , link version which should be a component extending from the link-to and x-tag components. x-tag-link-to ,链接版本,它应该是从link-tox-tag组件扩展的组件。

Since you cannot extend from two components, I moved the logic in the x-tag component into a tag mixin. 由于您不能从两个组件扩展,因此我将x-tag组件中的逻辑移到了tag mixin中。 So the components ended up like this: 因此组件最终如下所示:

  • x-tag , compoents that implements the tag mixin. x-tag ,实现tag混合的组件。
  • x-tag-link-to , compoents that extends the link-to component and also implements the tag mixin. x-tag-link-to ,扩展了link-to组件并实现tag mixin的组件。

This solves the problem, but is confusing having the logic in several files, also I have a lot more components like the tag that also have a link version, filling the mixins folder with a lot of mixins which have almost the whole component logic. 这解决了问题,但在多个文件中具有逻辑混乱,我也有很多组件,例如标签也有链接版本,用很多具有几乎整个组件逻辑的mixins填充mixins文件夹。 That just feels wrong , or is this the right approach? 那只是感觉不对 ,还是这是正确的方法?

I can provide code examples if needed. 如果需要,我可以提供代码示例。

I ended up using mixins, as Gennady Dogaev said in a comment. 正如Gennady Dogaev在评论中所说,我最终使用了mixins。

The result is this: 结果是这样的:

  • mixins/components/x-tag : has the tag component logic. mixins/components/x-tag :具有标签组件逻辑。
  • components/x-tag : empty component implementing the mixin. components/x-tag :实现混入的空组件。
  • components/x-tag-link-to : link-to component extended to implement the mixin. components/x-tag-link-tolink-to组件的扩展,以实现mixin。

I discarded composition, although it seems the right path, mapping the implementation of the inside components to the containing component would be a nightmare to mantain in the long run. 我放弃了组合,尽管这似乎是正确的道路,但从长远来看,将内部组件的实现映射到包含组件将是一个噩梦。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM