重新绘制和渲染
main.js
import {render, Component, createElement} from './toy-react.js'
// window.a = <div id="app" class="head"></div>
class Hello extends Component {
constructor () {
super()
this.state = {
count: 0
}
}
render () {
return <div>
<button onClick={() => {this.state.count++; this.rerender()} }>add</button>
<p>{this.state.count.toString()}</p>
{this.children}
</div>
}
}
window.a = <Hello id="app" class="head">
<span>1</span>
<span>2</span>
<span><h1>3</h1><h1>4</h1></span>
hello
</Hello>
render(window.a, document.body)
toy-react.js
const RENDER_TO_DOM = Symbol('render to dom')
export class Component {
constructor() {
this.props = Object.create(null);
this.children = [];
this._root = null;
this._range = null;
}
setAttribute(name, value) {
this.props[name] = value
}
appendChild(component) {
this.children.push(component)
}
[RENDER_TO_DOM](range) {
this._range = range
this.render()[RENDER_TO_DOM](range)
}
rerender() {
this._range.deleteContents()
this[RENDER_TO_DOM](this._range)
}
// get root() {
// if (!this._root) {
// this._root = this.render().root
// }
// return this._root
// }
}
class ElementWrapper {
constructor(type) {
this.root = document.createElement(type)
}
setAttribute(name, value) {
// 过滤事件, 如onClick
if (name.match(/^on([\s\S]+)$/)) {
console.log(RegExp.$1)
// 绑定事件, Click转click
this.root.addEventListener(RegExp.$1.replace(/^[\s\S]/, c => c.toLowerCase()), value)
} else {
this.root.setAttribute(name, value)
}
this.root.setAttribute(name, value)
}
appendChild(component) {
// this.root.appendChild(component.root)
let range = document.createRange()
range.setStart(this.root, this.root.childNodes.length)
range.setEnd(this.root, this.root.childNodes.length)
component[RENDER_TO_DOM](range)
}
[RENDER_TO_DOM](range){
range.deleteContents()
range.insertNode(this.root)
}
}
class TextWrapper {
constructor(content) {
this.root = document.createTextNode(content)
}
[RENDER_TO_DOM](range){
range.deleteContents()
range.insertNode(this.root)
}
}
export function createElement(tagName, attributes, ...rest) {
let element
if (typeof tagName == 'string') {
element = new ElementWrapper(tagName)
} else {
element = new tagName
}
if (typeof attributes === 'object' && attributes instanceof Object) {
for (const key in attributes) {
element.setAttribute(key, attributes[key])
}
}
let insertChildren = (children) => {
console.log(children)
for(const child of children) {
if (typeof child == 'string') {
child = new TextWrapper(child)
}
if ((typeof child == 'object') && (child instanceof Array)) {
insertChildren(child)
} else {
element.appendChild(child)
}
}
}
insertChildren(rest)
return element
}
export function render(component, parentElement) {
// parentElement.appendChild(component.root)
let range = document.createRange()
range.setStart(parentElement, 0)
range.setEnd(parentElement, parentElement.childNodes.length)
component[RENDER_TO_DOM](range)
}