前端組件化-抽象公共組件類

優化上次的組件化小demohtml

上次的組件化demo只是爲了簡單的實現前端組件化的思想,此次咱們稍微優化一下抽離公共類前端

下面代碼

htmlapp

<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 能夠解決。優化

相關文章
相關標籤/搜索