[] Like-react handwriting of a framework similar to react

Usually write react, do not understand is how the internal jsx into vdom, then rendered on screen, and when the updated data stream, the view is how to update it.

 

So after I went through a lot of information, their own version of a simple handwritten react, which would be able to react understand the basic operation mechanism.

 

react a very convenient place is that we can write like a native html did write assembly, which is jsx grammar, then how jsx dom into it. Firstly babel syntax tree parsing transformed into vdom, its structure is probably

{
    type: 'div',
    props: { id: 'container' },
    children: ['xxxxx']
}  

Following the adoption of internal render method will react vdom into dom node.

render method to achieve the following:

const _render = (vdom, parent = null) => {
    // custom component 经过 babel 转义 然后 React.createElement 返回的 vdom.type 类型是 function
    // <p id="label">title</p> vdom = { type: 'p', props: {id: 'label'}, children: ['title']}
    const mount = parent ? (el => parent.appendChild(el)) : (el => el);
    if (typeof vdom === 'string' || typeof vdom === 'number') {
      return mount(document.createTextNode(vdom));
    } if (typeof vdom === 'boolean' || vdom === null) {
      return mount(document.createTextNode(''));
    } if (typeof vdom === 'object' && typeof vdom.type === 'function') {
      return Component.render(vdom, parent);
    } if (typeof vdom === 'object' && typeof vdom.type === 'string') {
      const dom = mount(document.createElement(vdom.type));
      for (const child of [].concat(...vdom.children)) _render(child, dom);
      for (const prop in vdom.props) {
        if (Object.prototype.hasOwnProperty.call(vdom.props, prop)) {
          setAttribute(dom, prop, vdom.props[prop]);
        }
      }
      return dom;
    }
    throw new Error(`Invalid VDOM: ${vdom}.`);
  };

It is worth mentioning that when ReactDOM.render (), will first traverse all nodes, then the node instantiation, componentWillMount method call, then the call inside render vdom into real dom, receiving a key identifier value, which is updated It will come in handy when components. Then call componentDidMount method.

 

Then talk about what happens when react update state. As we all know, the traditional comparison of two trees are the same time complexity is O (n ^ 3), and react based on a comparison of time complexity of rules down to O (n), which greatly improves the computing time and improve the rendering speed. Therefore react patch method when updating the state have done. In fact, react comparison algorithm is based on: a tree two types of nodes are not at the same time the whole tree are replaced; 2 when the same key value of the node directly compare all child nodes recursively.

 

See detailed implementation:  https://github.com/Vxee/like-react

Guess you like

Origin www.cnblogs.com/fjl-vxee/p/11027025.html
Recommended