组件可能是函数还可能是类,我们知道只需继承 Component 类就是 react 的组件。
function Box(){ return ( <div className='box' size="24"> hello,<span>zidea</span> </div> )}
创立一个函数,函数名为 Box 函数返回一个 jsx 对象
ReactDOM.render(<Box name={title}/>,document.querySelector("#root"));
传入一个名称为 title 的对象,
function _render(vnode){ //TODO if(vnode === undefined ) return; // vnode is equal string if(typeof vnode === 'string'){ //create textNode return document.createTextNode(vnode) } // deconstruct vnode const {tag,attrs} = vnode; //create dom object const dom = document.createElement(tag) if(attrs){ // property key: className box Object.keys(attrs).forEach(key=>{ const val = attrs[key] setAttribute(dom,key,val) }) } vnode.children.forEach(child=>render(child,dom)) return dom; }
在 javascript 中,假如函数名称以下划线开头通常是私有方法。这里把渲染设置为私有方法,也就是渲染逻辑放置在_render
方法中。而后 _render
方法主要就是讲虚拟节点解决 dom 节点返回出来。
return dom;
返回 dom 而不是将 dom 增加到容器节点中return document.createTextNode(vnode)
通常function render(vnode,container){ container.appendChild(_render(vnode))}
if(vnode === undefined || vnode === null || typeof vnode === 'boolean') vnode = '';
判断 tag 是函数,tag 可能是函数组件或者类组件if(typeof vnode.tag === 'function')
通过虚拟节点 tag 值来判断能否为组件,而后按组件进行解决
const comp = createComponent(vnode.tag,vnode.attrs);
setComponentProps(comp,vnode.attrs);
return comp.base;
这里我们不能返回组件,而需要将节点对象挂接到 comp 的 base 属性上,而后返回comp.base
的个节点对象。function createComponent(comp,props){ //declare component instance let instance; // class component case if(comp.prototype && comp.prototype.render){ instance = new comp(propos) }else{ // function component case //conver function component to class component instance = new Component(props) //constructor prefer to function(component) instance.constructor = comp; //define render function instance.render = function(){ //return jsx object return this.constructor(props) } } return instance;}
react
文件夹下创立一个 component.js
类其中定义 Component 类class Component{ constructor(props = {}){ this.props = props; this.state = {}; }}export default Component;
- 在构造函数接收 props 参数,这是从外部传入的参数,而后内部维护一个状态对象 state
instance.render = function(){ //return jsx object return this.constructor(props)}
function setComponentProps(comp,props){ //设置组件的属性 comp.propos = props; renderComponent(comp)}
function renderComponent(comp){ let base; //call render method to return jsx object const renderer = comp.render(); //conver jsx to dom obj base = _render(renderer); console.log(base) comp.base = base}