優化上次的組件化小demo
上次的組件化demo只是為了簡單的實現前端組件化的思想,這次我們稍微優化一下抽離公共類
下面代碼
html
<div id="wrapper"></div>
復制代碼
js
/* DOM字符串轉DOM節點 */
const createStringToDom = str => {const ele = document.createElement('div');ele.innerHTML = str;return ele;
}/* Mount */
const mount = (component, wrapper) => {wrapper.appendChild(component._renderDom());component.changeState = (oldEl, newEl) => {wrapper.insertBefore(newEl, oldEl);wrapper.removeChild(oldEl);}
}/* Components */
class Components {constructor (props = {}) {this.props = props;}setState (context) {const oldEl = this.el;Object.assign(this.state, context)this._renderDom();if (this.changeState) {this.changeState(oldEl, this.el)}}_renderDom () {this.el = createStringToDom(this.render());this.el.addEventListener('click', this.clickEvent.bind(this), false);return this.el;}
}/* ZanButton */
class ZanButton extends Components {constructor (props) {super(props);this.state = {isLike: false}}clickEvent () {this.setState({isLike: !this.state.isLike})}render () {return (`<button style="background-color: ${ this.props.bgColor }">${ this.state.isLike ? '取消' : '點贊' }</button>`)}
}const wrapper = document.getElementById('wrapper');
mount(new ZanButton(), wrapper);
mount(new ZanButton({bgColor: 'red'
}), wrapper);
復制代碼
通過抽離公共類繼續拆分代碼,使得組件復用更簡單容易,DOM操作也是自動完成的無需我們的介入,不過這里還有一個問題就是不斷的刪除,插入DOM節點會引起頁面的重排,加大開銷,這個問題通過 Virtual DOM 可以解決。