const stringToDom = (domString)=>{
let oDiv = document.createElement('div');
oDiv.innerHTML = domString;
return oDiv;
}
class Component{
constructor(props={}){
this.props = props
}
setState(state){
const oldEl = this.el;
this.state = state;
this.el = this._renderDOM();
if(this.onStateChange) this.onStateChange(oldEl,this.el)
}
_renderDOM(){
this.el = stringToDom(this.render())
if(this.onClick){
this.el.addEventListener('click',this.onClick.bind(this),false)
}
return this.el
}
}
const mount = (component,wrapper)=>{
wrapper.appendChild(component._renderDOM())
component.onStateChange = (oldEl,newEl)=>{
wrapper.insertBefore(newEl,oldEl);
wrapper.removeChild(oldEl)
}
}
class LikeBtn extends Component{
constructor(props){
super(props)
this.state={
isLike:true
}
}
onClick(){
this.setState({
isLike:!this.state.isLike
})
}
render(){
return (`
<button class="like-btn" style="background-color:${this.props.bgColor}">
<span class="like-btn">${this.state.isLike?"点赞":"取消"}
</span>
</button>
`)
}
}
mount(new LikeBtn({bgColor:'red'}),document.querySelector('.wrapper'))
// class likeButton {
// constructor(){
// this.state = {
// isLike:true
// }
// }
// changeLikeText(){
// this.setState({
// isLike:!this.state.isLike
// })
// }
// setState(state){
// const old = this.el;
// this.state=state;
// this.el = this.render();
// if(this.onStateChange) this.onStateChange(old,this.el)
// }
// render() {
// this.el = stringToDom(`
// <button class="like-btn">
// <span class="like-text">
// ${this.state.isLike?"点赞":"取消"}
// </span>
// <span>��</span>
// </button>
// `);
// this.el.addEventListener('click',this.changeLikeText.bind(this))
// return this.el
// }
// }
// const wrap = document.querySelector('.wrapper');
// const like_btn_1 = new likeButton();
// console.log(wrap)
// wrap.appendChild (like_btn_1.render());
// like_btn_1.onStateChange = (oldEl, newEl) => {
// wrap.insertBefore(newEl,oldEl);
// wrap.removeChild(oldEl)
// }
// like_btn_1.onStateChange = (oldEl, newEl) => {
// wrapper.insertBefore(newEl, oldEl) // 插入新的元素
// wrapper.removeChild(oldEl) // 删除旧的元素
// }
<div class="wrapper">
</div>