1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
| class Wrapper{ constructor(content){ this.root = document.createElement(content) } setAttribute(name,value){ this.root.setAttribute(name,value) } appendChild(vchild){ vchild.mountTo(this.root) } mountTo(parent) { parent.appendChild(this.root) } } class TextWrapper{ constructor(content){ this.root = document.createTextNode(content) } mountTo(parent) { parent.appendChild(this.root) } } export class Component{ setAttribute(name, value){ this[name] = value; } mountTo(parent){ let vdom = this.render() vdom.mountTo(parent) } } export let ToyReact = { createElement(type,attributes,...children){ let element if(typeof type === 'string') element = new Wrapper(type) else element = new type
for(let name in attributes){ element.setAttribute(name,attributes[name]) } let insertChildren=(children)=>{ for(let child of children){ if(typeof child === 'object' && child instanceof Array){ insertChildren(child) }else{ if(!(child instanceof Component) && !(child instanceof Wrapper) && !(child instanceof TextWrapper)){ child = String(child) } if(typeof child === 'string') child = new TextWrapper(child); element.appendChild(child)
} } } insertChildren(children)
return element }, render(vdom, element){ vdom.mountTo(element) } }
import {ToyReact,Component} from './ToyReact' class MyComponent extends Component{ render(){ return <div> <span>dog</span> <span>cat</span> <div>{true}</div> </div> } } let a = <MyComponent name="a" id="aaa"></MyComponent> ToyReact.render( a, document.body )
|