这样设计一个可扩展、通用的、健壮性组件

比眉伴天荒 2022-09-13 13:27 288阅读 0赞

点击上方关注 小生方勤,一起学习,天天进步

前言

组件是页面不可或缺的部分,而设计组件就成为了前端同学每日工作。

所以

一位程序员的职业生涯大约十年,只有人寿命的十分之一。前端项目只是你生活工作的一部分,而你却是它的全部,你是他的灵魂。请放下长时间的游戏、工作时的摸鱼。多学习来以最完美的状态好好陪你项目!

正文

这篇文章将会以本人所认知的角度去对组件的封装设计展开思考。如果你对我的观点,方式,又或者你有更好的方式,更优的设计模式,不妨在评论区一起讨论 思考, 交流是进步的必经之路。

知识点

  • 组件是如何分类的
  • Vue 和 React 封装组件模式
  • 怎样才是一个好的可扩展、通用的、健壮性组件
  • 思考讨论,提出问题

组件是如何分类的

  • 业务组件
  • 通用组件(非业务组件)

    • UI组件

acd06b67f8621c2d2827d48b4025dd98.png 1627627583874_8398E85B-D83D-430B-AF41-D4D3F8CF04C0.png

无论是 业务组件 或者 通用组件都具备组件本质所包含的三个性质扩展通用健壮

  • 扩展性:在原有组件基础上可 二次封装 扩展成新的组件符合设计的开闭原则
  • 通用性:根据组件接受的参数组件中与业务的解耦比来衡量组件的通用性,并不是通用性占比100%的组件就是最好的组件,需要根据 不同的场景 分析
  • 健壮性:避免组件中参数处理函数执行过程可能出现的奔溃和错误导致程序的直接挂断,单测以对组件内部 做好边界处理,异常错误的捕获来衡量这一标准

业务组件

服务与业务的组件称为业务组件,项目中组件的划分是分页面级组件全局级别组件

  1. --- componentes
  2. --- pages
  3. 复制代码

而结构一般是这样

componentes 中存放的组件往往 具有当前项目 中的多个 场景 复用 才会进行设计与封装

Vue中的组件

  1. <template>
  2. ....
  3. </template>
  4. <script>
  5. export default {
  6. props: {
  7. ...
  8. },
  9. data () {
  10. ....
  11. },
  12. methods: {
  13. ....
  14. }
  15. }
  16. </script>
  17. 复制代码

React中的组件

  1. import React, { Component } from react ;
  2. export default class Demo extends Component {
  3. state = {
  4. };
  5. componentDidMount() {
  6. ...
  7. }
  8. render() {
  9. const { .... } = this.props;
  10. return (
  11. <div>
  12. ....
  13. </div>
  14. );
  15. }
  16. }
  17. 复制代码

这是目前两个 两个框架最基本的组件封装 模板

而你在封装组件的时候是否考虑过一些问题

  • 组件的可维护性?
  • 组件的可读性?
  • 扩展性、健壮性、通用性?
  • 这个组件是否需要封装抽离?
  • 组件是否和业务强关联?

这些问题在组件封装开始编码之前你是否都考虑过了

凡是组件不断扩展,使其通用性提升,必然就会降低组件的 易用性质

而不断丰富一个组件,也会导致其组件代码过长,组件使命不单一,不易读不易维护

像Vue 和 React 推荐 一个组件代码长度在 200 - 500 行最佳

业务中的组件往往区分

82d5811a1c1bd925dda963ed58f3c99b.png 1627627666905_1E9DC37D-8E0E-45C7-814A-63CA34D3936C.png

  • 容器组件负责处理业务相关逻辑,注册业务相关钩子,传入相应的熟悉和插槽等
  • 视图组件则负责数据的呈现,交互的实现

66c88f7294ae9ce84b1ef835a7675997.png 1627634474901_9F20476A-9B8A-4360-A907-C79218F72E55.png

容器组件往往不可复用

视图组件则根据组件的样式交互 判断组件在项目中的 频率 来抉择是否封装

视图数据 解耦 又能搭配 可以很好的提升组件的 可读,易维护性

这个组件是否需要封装抽离?

这可能是新前端同学容易遇到的问题

不是所以 DOM 结构 都需要 抽离

你需要对你所负责的项目 UI走向 有着全局的洞察力,如果不确认的是否需要封装,建议不封装

下次业务中存在与原来视图 UI 相同的需求 再进行封装设计,而不是快速 Copy

组件是否和业务强关联?

通常情况,组件中的大量数据来源 当前组件的接口请求。没有依赖或者几乎不依赖外部传入的props等,称为业务强关联组件,放弃组件封装的想法。

怎样才是一个好的可扩展、通用的、健壮性组件?

我们可以参考一下star高的 Ant designElement 来学习

Ant design 中 rc-switch

  1. import * as React from react ;
  2. import classNames from classnames ;
  3. import useMergedState from rc-util/lib/hooks/useMergedState ;
  4. import KeyCode from rc-util/lib/KeyCode ;
  5. const Switch = React.forwardRef(
  6. (
  7. {
  8. prefixCls = rc-switch ,
  9. className,
  10. checked,
  11. defaultChecked,
  12. disabled,
  13. loadingIcon,
  14. checkedChildren,
  15. unCheckedChildren,
  16. onClick,
  17. onChange,
  18. onKeyDown,
  19. ...restProps
  20. },
  21. ref,
  22. ) => {
  23. const [innerChecked, setInnerChecked] = useMergedState<boolean>(false, {
  24. value: checked,
  25. defaultValue: defaultChecked,
  26. });
  27. function triggerChange(
  28. newChecked: boolean,
  29. event: React.MouseEvent<HTMLButtonElement> | React.KeyboardEvent<HTMLButtonElement>,
  30. ) {
  31. let mergedChecked = innerChecked;
  32. if (!disabled) {
  33. mergedChecked = newChecked;
  34. setInnerChecked(mergedChecked);
  35. onChange?.(mergedChecked, event);
  36. }
  37. return mergedChecked;
  38. }
  39. function onInternalKeyDown(e) {
  40. if (e.which === KeyCode.LEFT) {
  41. triggerChange(false, e);
  42. } else if (e.which === KeyCode.RIGHT) {
  43. triggerChange(true, e);
  44. }
  45. onKeyDown?.(e);
  46. }
  47. function onInternalClick(e) {
  48. const ret = triggerChange(!innerChecked, e);
  49. // [Legacy] trigger onClick with value
  50. onClick?.(ret, e);
  51. }
  52. const switchClassName = classNames(prefixCls, className, {
  53. [`${prefixCls}-checked`]: innerChecked,
  54. [`${prefixCls}-disabled`]: disabled,
  55. });
  56. return (
  57. <button
  58. {...restProps}
  59. type="button"
  60. role="switch"
  61. aria-checked={innerChecked}
  62. disabled={disabled}
  63. className={switchClassName}
  64. ref={ref}
  65. onKeyDown={onInternalKeyDown}
  66. onClick={onInternalClick}
  67. >
  68. {loadingIcon}
  69. <span className={`${prefixCls}-inner`}>
  70. {innerChecked ? checkedChildren : unCheckedChildren}
  71. </span>
  72. </button>
  73. );
  74. },
  75. );
  76. Switch.displayName = Switch ;
  77. export default Switch;
  78. 复制代码
  • 直接脱离 UI
  • 接受参数,处理钩子

Ant design 则是对API 和 UI 的二次封装

进而体现了 React Components[1] 的组件的 可扩展性

再看看

Element UI 的 Switch

  1. <template>
  2. <div
  3. class="el-switch"
  4. :class="{ is-disabled : switchDisabled, is-checked : checked }"
  5. role="switch"
  6. :aria-checked="checked"
  7. :aria-disabled="switchDisabled"
  8. @click.prevent="switchValue"
  9. >
  10. <input
  11. class="el-switch__input"
  12. type="checkbox"
  13. @change="handleChange"
  14. ref="input"
  15. :id="id"
  16. :name="name"
  17. :true-value="activeValue"
  18. :false-value="inactiveValue"
  19. :disabled="switchDisabled"
  20. @keydown.enter="switchValue"
  21. >
  22. <span
  23. :class="[ el-switch__label , el-switch__label--left , !checked ? is-active : ]"
  24. v-if="inactiveIconClass || inactiveText">
  25. <i :class="[inactiveIconClass]" v-if="inactiveIconClass"></i>
  26. <span v-if="!inactiveIconClass && inactiveText" :aria-hidden="checked">{
  27. { inactiveText }}</span>
  28. </span>
  29. <span class="el-switch__core" ref="core" :style="{ width : coreWidth + px }">
  30. </span>
  31. <span
  32. :class="[ el-switch__label , el-switch__label--right , checked ? is-active : ]"
  33. v-if="activeIconClass || activeText">
  34. <i :class="[activeIconClass]" v-if="activeIconClass"></i>
  35. <span v-if="!activeIconClass && activeText" :aria-hidden="!checked">{
  36. { activeText }}</span>
  37. </span>
  38. </div>
  39. </template>
  40. <script>
  41. import emitter from element-ui/src/mixins/emitter ;
  42. import Focus from element-ui/src/mixins/focus ;
  43. import Migrating from element-ui/src/mixins/migrating ;
  44. export default {
  45. name: ElSwitch ,
  46. mixins: [Focus( input ), Migrating, emitter],
  47. inject: {
  48. elForm: {
  49. default:
  50. }
  51. },
  52. props: {
  53. value: {
  54. type: [Boolean, String, Number],
  55. default: false
  56. },
  57. disabled: {
  58. type: Boolean,
  59. default: false
  60. },
  61. width: {
  62. type: Number,
  63. default: 40
  64. },
  65. activeIconClass: {
  66. type: String,
  67. default:
  68. },
  69. inactiveIconClass: {
  70. type: String,
  71. default:
  72. },
  73. activeText: String,
  74. inactiveText: String,
  75. activeColor: {
  76. type: String,
  77. default:
  78. },
  79. inactiveColor: {
  80. type: String,
  81. default:
  82. },
  83. activeValue: {
  84. type: [Boolean, String, Number],
  85. default: true
  86. },
  87. inactiveValue: {
  88. type: [Boolean, String, Number],
  89. default: false
  90. },
  91. name: {
  92. type: String,
  93. default:
  94. },
  95. validateEvent: {
  96. type: Boolean,
  97. default: true
  98. },
  99. id: String
  100. },
  101. data() {
  102. return {
  103. coreWidth: this.width
  104. };
  105. },
  106. created() {
  107. if (!~[this.activeValue, this.inactiveValue].indexOf(this.value)) {
  108. this.$emit( input , this.inactiveValue);
  109. }
  110. },
  111. computed: {
  112. checked() {
  113. return this.value === this.activeValue;
  114. },
  115. switchDisabled() {
  116. return this.disabled || (this.elForm || {}).disabled;
  117. }
  118. },
  119. watch: {
  120. checked() {
  121. this.$refs.input.checked = this.checked;
  122. if (this.activeColor || this.inactiveColor) {
  123. this.setBackgroundColor();
  124. }
  125. if (this.validateEvent) {
  126. this.dispatch( ElFormItem , el.form.change , [this.value]);
  127. }
  128. }
  129. },
  130. methods: {
  131. handleChange(event) {
  132. const val = this.checked ? this.inactiveValue : this.activeValue;
  133. this.$emit( input , val);
  134. this.$emit( change , val);
  135. this.$nextTick(() => {
  136. // set input s checked property
  137. // in case parent refuses to change component s value
  138. this.$refs.input.checked = this.checked;
  139. });
  140. },
  141. setBackgroundColor() {
  142. let newColor = this.checked ? this.activeColor : this.inactiveColor;
  143. this.$refs.core.style.borderColor = newColor;
  144. this.$refs.core.style.backgroundColor = newColor;
  145. },
  146. switchValue() {
  147. !this.switchDisabled && this.handleChange();
  148. },
  149. getMigratingConfig() {
  150. return {
  151. props: {
  152. on-color : on-color is renamed to active-color. ,
  153. off-color : off-color is renamed to inactive-color. ,
  154. on-text : on-text is renamed to active-text. ,
  155. off-text : off-text is renamed to inactive-text. ,
  156. on-value : on-value is renamed to active-value. ,
  157. off-value : off-value is renamed to inactive-value. ,
  158. on-icon-class : on-icon-class is renamed to active-icon-class. ,
  159. off-icon-class : off-icon-class is renamed to inactive-icon-class.
  160. }
  161. };
  162. }
  163. },
  164. mounted() {
  165. /* istanbul ignore if */
  166. this.coreWidth = this.width || 40;
  167. if (this.activeColor || this.inactiveColor) {
  168. this.setBackgroundColor();
  169. }
  170. this.$refs.input.checked = this.checked;
  171. }
  172. };
  173. </script>
  174. 复制代码

很直观的看出, 除了语法 方面 封装设计组件UI的最佳方式

  • 零业务代码
  • 优秀的UIAPI设计
  • 易学易用

我们再看看另外一种封装组件的方式

4748c191df5985614ab562bc05f0cccb.png 1627634757928_22274B24-4A7F-4B1B-8307-3A565B77A956.png

React For Menu

da1519a9992bfa4e7cbe0f040c5478c6.png carbon (1).png

这是 React 配套组件的封装 的一种思路

  • 创建 context 管理 组件组 的数据流
  • 父组件中存在判断 子组件的类型 增加健壮性
  • index 挂载 分别导出组件

Vue For Menu

  1. <template>
  2. <div
  3. class="menu"
  4. // 事件绑定
  5. >
  6. // menuItem
  7. <slot></slot>
  8. </div>
  9. </template>
  10. <script>
  11. export default {
  12. mixins: [...],
  13. name: Menu ,
  14. componentName: Menu ,
  15. inject: {
  16. menu: {
  17. default:
  18. },
  19. },
  20. provide() {
  21. return {
  22. menu : this
  23. };
  24. }
  25. }
  26. </script>
  27. 复制代码

Vue - UI 组件的设计封装中 , 经常使用 provide,inject来组件通信.

Vue 除了使用 slot 还可以使用 jsx & function component 来实现如此效果,其设计思想和 React 大同小异

Vue3Ant design for Vue 中大量使用 jsx 来 封装 组件

下面简单总结一下

  • 组件中的 UI数据 业务尽量 分离
  • UI视图 组件中 不该包含 业务代码
  • 组件设计之初考虑通用、易用、扩展、健壮稳定 以及 良好的代码结构、Api设计使用

思考讨论,提出问题

  • 你有不同的或者更好的设计封装组件的技巧Demo
  • 你是如何判断组件是否封装的?如何设计组件的?
  • 回想一下你设计的组件 代码Api命名 是否给其他同学带来不便
  • 等等…..

根据以上的问题思考 或者 你有不同的想法 不妨在评论区中我们一起探讨,学习!

关于本文

来源:遇见同学

https://juejin.cn/post/6991261103141421092

点个『在看』支持下 245e572a9c6a3a006bdb0afa97953262.gif

发表评论

表情:
评论列表 (有 0 条评论,288人围观)

还没有评论,来说两句吧...

相关阅读