一、作用
- 提高代码的复用性
- 提高代码的可维护性
二、实现
组件机制
- 组件的创建和挂载(new/appendTo)
new:在prama函数中进行class实例创建
- 生命周期
通用的生命周期有:
创建-created 挂载后mounted 卸载 unmount
一个组件都是由生到死的,从最开始创建再到渲染,再到挂载,而js的改变和用户的输入,可能会引起组件的渲染。
- 事件
- attribute/property
Attribute 通常是固定的字符串 ,Attribute 会影响到 property,类似描述外表的一个概念
Property 不是特别理解 一般来说和attribute对等就行,不用太过区分
- 方法当前组件所具有的方法
- children子节点的存储,做一些特定的控制
- state
state表示组件内部的状态,一般来说,state的变化基本都来自于终端用户的输入(包括时间),state会影响children
- config
config基本用不到,在逐渐constructor的时候 ,赋值即可。
config是一次性的 ,只能由 JS Set。
- 描述语言
JSX 一种语法糖, React使用
特点:
- JSX 执行更快,因为它在编译为 JavaScript 代码后进行了优化。
- 它是类型安全的,在编译过程中就能发现错误。
- 使用 JSX 编写模板更加简单快速。
- 组件的基础能力
手势:
封装一个手势库 ,实现移动端和pc端兼容的手势,常用的有flick、pan
组件体系
页面开发
基础组件例子:
const PROPERTY_SYMBOL = Symbol("property");const ATTRIBUTE_SYMBOL = Symbol("attribute");const EVENT_SYMBOL = Symbol("event");const STATE_SYMBOL = Symbol("state");export default class Div { constructor(config){ this[PROPERTY_SYMBOL] = Object.create(null); this[ATTRIBUTE_SYMBOL] = Object.create(null); this[EVENT_SYMBOL] = Object.create(null); this[STATE_SYMBOL] = Object.create(null); this[PROPERTY_SYMBOL].children = []; this.created(); } appendTo(element){ element.appendChild(this.root); this.mounted(); } created(){ this.root = document.createElement("div"); this[STATE_SYMBOL].h = 0; } mounted(){ } unmounted(){ } update(){ } appendChild(child){ this.children.push(child); child.appendTo(this.root); } get children(){ return this[PROPERTY_SYMBOL].children; } getAttribute(name){ if(name == "style") { return this.root.getAttribute("style"); } return this[ATTRIBUTE_SYMBOL][name] } setAttribute(name, value){ if(name == "style") { this.root.setAttribute("style", value); } return this[ATTRIBUTE_SYMBOL][name] = value; } addEventListener(type, listener){ if(!this[EVENT_SYMBOL][type]) this[EVENT_SYMBOL][type] = new Set; this[EVENT_SYMBOL][type].add(listener); } removeEventListener(type, listener){ if(!this[EVENT_SYMBOL][type]) return; this[EVENT_SYMBOL][type].delete(listener); } triggerEvent(type){ if(!this[EVENT_SYMBOL][type]) return; for(let event of this[EVENT_SYMBOL][type]) event.call(this); }}