react 渲染

React渲染

JSX如何生成element

    return(
        <div className="box">
            <div> header </div>
            hello world
        </div>
    )

他会经过babel编译成React.createElement的表达式

return(
    React.createElement(
        'div',
        {className:'box'},
        React.createElement(
            'div',
            null,
            'header'
        ),
        'hello world'
    )
)

createElement()是用来组成虚拟DOM树

createElement的三个参数

  1. type -> 标签

  2. attributes => 属性标签,没有的话,可以为null

  3. children => 标签的子节点

最后的element对象的值

{
    type:'div',
    props:{
        className:'box',
        children:[
            {
                type: "div",
                props:{
                    children:"header"
                }
            },
            "Hello world"
        ]
    }
}

element如何生成真实节点

而其中的ReactDOMComponent等等,属于React的私有类,React自己使用 ,不会暴露给用户的
常用的有:mountComponent,updateConponent等,而我们自定义的生命周期函数以及render函数都是在私有类的方法里被调用

ReactDOMComponent 作用

ReactDOMComponent的mountComponent方法,这个方法的作用是:将element转成真实DOM节点,并且插入到相应的container里,然后返回markup(realDOM)

简单实现

{
    type: 'div',
    props: {
    className: 'box',
      children: 'Hello world',
    }
}

mountComponent(container) {
  const domElement = document.createElement(this._currentElement.type);
  const textNode = document.createTextNode(this._currentElement.props.children);

  domElement.appendChild(textNode);
  container.appendChild(domElement);
  return domElement;
}

ReactCompositeComponentWrapper 作用

这个类的mountComponent方法作用是:实例化自定义组件,最后是通过递归调用到ReactDOMComponentmountComponent方法来得到真实DOM。

渲染规则

猜你喜欢

转载自www.cnblogs.com/strongtyf/p/12359339.html