【金秋打卡】第16天 实现Popup弹层组件结构
2022/11/9 4:24:12
本文主要是介绍【金秋打卡】第16天 实现Popup弹层组件结构,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
课程名称:TypeScript封装播放器组件
课程章节: 第4章 4-1 组件框架搭建
课程讲师:西门老舅
课程内容:
今天学习的内容是实现 Popup组件的框架。
组件基本结构
根据前面的需求分析,弹层组件分为两部分:
- 结构、功能:popup.ts
- 样式:popup.css
在 src/components 目录下新建 Popup 目录,存放弹层组件的内容:
src/components |- Popup |- index.ts |- index.css
使用面向对象的思想来实现组件,使用一个函数对外暴露:
class Popup { } function popup() { return new Popup() } export default popup
这是一种单例设计模式。
实现功能
前面分析了弹层组件的配置参数:
- width/height:弹层宽高,默认和父容器保持一致
- title:弹层标题
- content:弹层内容展示
- position:弹层位置,默认水平垂直居中
- mask:遮罩
使用 TypeScript 提供的接口来声明一个配置对象的类型:
interface IPopup { width?: string, height?: string, title?: string, position?: string, mask?: boolean, content?: () => void }
在构造函数中处理配置对象,通过 Object.assign 方法来合并用户传入的配置和默认配置,这是一个常用技巧:
class Popup { constructor(private options: IPopup) { this.options = Object.assign({ width: '100%', height: '100%', title: '', position: 'center%', mask: true, content: () => {} }, options) } }
组件规范约束
一个项目中会有大大小小很多个组件。这些组件在编写时需要有一个统一的规范。
依旧是使用接口来定义一个组件的接口,来约束组件的编写。
interface IComponent { tempContainer: HTMLElement, // 组件挂载的容器 init: () => void, // 初始化 template: () => void, // 创建模板 handle: () => void // 处理事件 }
类需要实现接口,使用 implements 关键字:
class Popup implements IComponent { tempContainer!: HTMLElement; constructor(private options: IPopup) { // ..... } init() { this.template() } template() { this.tempContainer = document.createElement('div') this.tempContainer.innerHTML = ` ` document.body.appendChild(this.tempContainer) } handle() {} } function popup(options: IPopup) { return new Popup(options) } export default popup
课程收获
这节课学习了如何搭建组件的基本结构,通常会使用面向对象思想去封装组件,然后使用 TS 接口来对组件的构造参数类型和组件,进行一定的约束。
这篇关于【金秋打卡】第16天 实现Popup弹层组件结构的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15鸿蒙生态设备数量超8亿台
- 2024-05-13TiDB + ES:转转业财系统亿级数据存储优化实践
- 2024-05-09“2024鸿蒙零基础快速实战-仿抖音App开发(ArkTS版)”实战课程已上线
- 2024-05-09聊聊如何通过arthas-tunnel-server来远程管理所有需要arthas监控的应用
- 2024-05-09log4j2这么配就对了
- 2024-05-09nginx修改Content-Type
- 2024-05-09Redis多数据源,看这篇就够了
- 2024-05-09Google Chrome驱动程序 124.0.6367.62(正式版本)去哪下载?
- 2024-05-09有没有大佬知道这种数据应该怎么抓取呀?
- 2024-05-09这种运行结果里的10.100000001,怎么能最快改成10.1?