40行完成一個類似react的元件庫
阿新 • • 發佈:2019-04-13
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div class='wrapper'>
</div>
</body>
<script>
const createDOMFromString = (domString) => {
const div = document.createElement('div')
div.innerHTML = domString
return div
}
class Component {
constructor(props = {}) {
this.props = props;
}
setState(state) {
const oldEl = this.el;
this.state = state;
this._renderDOM()
if (this.onStateChange) this.onStateChange(oldEl, this.el);
}
_renderDOM() {
this.el = createDOMFromString(this.render());
if (this.onClick) {
this.el.addEventListener('click', this.onClick.bind(this), false);
}
return this.el;
}
}
class LikeButton extends Component {
constructor(props) {
super(props);
this.state = {
isLiked: false
};
}
onClick() {
this.setState({
isLiked: !this.state.isLiked
})
}
render() {
return `
<button class='like-btn' style="background-color:${this.props.bgColor}">
<span class='like-text'>${this.state.isLiked ? '取消' : '點贊'}</span>
<span>