Jsx what Ghost (together to write a jsx rendering engine)

Source: Internet
Author: User

Original address: https://jasonformat.com/wtf-is-jsx/

JSX 实际上很简单:读完这篇文章,你就会完全了解这个可选择的模版引擎

Subtitle: "Coexistence with JSX"

Annotations

You define this in each file and in each function, telling the translator (for example: Babel) The function name that each node needs to invoke during the runtime phase.

In the following example, we call the call "invoke the H () function for each node,"

/** @jsx h*/

Translated

If you have not used a translator, you should try to use it. Because it is more efficient to write, debug, test or run JS with es6/es2015. Among them, Babel is the most popular and the most recommended to use. Let's say you used Babel.

Now Babel not only provides support for converting your es6/es7+ syntax, but also provides direct out-of-the-box, conversion jsx support. You can use this feature directly.
Let's look at a simple example:
Have jsx before (how do you write code)

Have JSX after (you run the code)

var foo = h(‘div‘, {id:"foo"}, ‘Hello!‘);

You might see the second piece of code, and it feels good to create a UI with a function.

That's why I started from JSX: If you don't have this, it's still easy to write it out manually.

JSX is just a syntax sugar that's already very elegant.

Someone even the whole project with it Hypescript

Let's write a JSX renderer.

First, we want to define the H () function of the code call we're converting.

You can name this function as any name and I'm using H () because that's what this type of ' build ' function is called in Hypescript.
javascript function h(nodeName, attributes, ...args) { let children = args.length ? [].concat(...args) : null; return { nodeName, attributes, children }; }
Okay, it's that simple.
You're not familiar with es6/es2005?

1. The parameter ' ... ' is the remaining parameter, and the operator collects the remaining parameters into an array
2.concat (.... args) is the spread operator: This operator expands the array of parameters that were just passed into the arguments, and then to the Concat () method. The concat () is used here to merge the nested arrays of all child nodes.

Now we're outputting a nested JSON object through the H () method, which looks like this:

{  nodeName:"div",  attributes:{    "id":"foo"  },  children: ["Hello!"]}

So we just need a function that accepts the parameter format and outputs the actual DOM node

function Render(Vnode){      //Strings just convert to #text Nodes:    if(Vnode.Split)return Document.createTextNode(Vnode);    //Create a DOM element with the nodeName of our vdom element:     LetN= Document.createelement(Vnode.NodeName);    //Copy attributes onto the new node:     LetA= Vnode.attributes || {};    Object.Keys(a).ForEach(k= N.SetAttribute(k,A[K]));    //render (build) and then append child nodes:(Vnode.Children ||[]).ForEach(c= N.appendchild(Render(c)));    returnN;}

It's easy to understand this.
You can also think of the ' virtual Dom ' as a simple configuration of how to build a DOM structure.

The advantage of virtual DOM is that it is very lightweight. Lightweight objects refer to other lightweight objects. Very easy to optimize the application structure. This also means that it is not bound to any rendering logic and very slow DOM methods.

Using JSX

It is now known that JSX was converted to a call to H (). These function calls create a simple "virtual" dom tree.
We can use the render () function to create a matching "real" dom tree.

Just like this:

// JSX -> VDOM:let=<div id="foo">Hello!</div>;// VDOM -> DOM:let dom = render(vdom);// add the tree to <body>:document.body.appendChild(dom);  

Local templates, iterations, and logic: no new syntax

Unlike the limited concepts and limitations introduced in the template language, we have all the capabilities that JavaScript has.

' Local templates ' are concepts introduced by the non-logical/less logical template engine to reuse views in different places.

Iteration is one thing that almost all of the template syntax will introduce (and so do I). Similarly, for JSX: As with other JavaScript programs. You can choose a suitable iteration: [].foreach,[].map (), for and while loops, and so on.

Logically, as with iterations, template syntax is like redefinition. On the one hand, no logical template makes the view join logic inconvenient: unreasonable design, such as {{#if value}}, add logic to controller layer, make controller become very bloated. This avoidance approach creates a language that describes more complex logic and avoids the predictability and security implications.

On the other hand, the engine of code generation technology (a crude to inexcusable technique) often boasts the ability to have arbitrary JavaScript expressions to perform logic or even iterations. Here's the reason why we must avoid using this technology: Your code has been removed from the original ' Location ' (module, closure, or this tag) and executed elsewhere. This is unpredictable and unsafe for me.

JSX has all the capabilities of JavaScript and does not need to generate weird code in the build phase, and does not use eval ()

//Array of strings we want to show in a list: LetItems=[' foo ', ' Bar ', ' Baz '];//Creates one list item given some text:function Item(text){      return <Li>{Text}</li>;}//A "view" with "iteration" and "a partial":Let list = Render(  <ul>{Items.map(Item) }</ul>);

Render () returns a DOM node (<ul>), so we just add it to the DOM:

document.body.appendChild(list);  
Close together

Here is the full version of our virtual DOM rendering, with the style Codepen version below

ConstITEMS= ' Hello there people '.Split("');//Turn an Array into list items: LetList=Items= Items.Map* 2= <Li> {P} </li>);//view with a call out("partial")To generate a list from an Array:Let vdom =(  <div id= "foo" ><p>look, a simple JSX DOM renderer!</p>        <Ul>{ List(ITEMS)}</ul></div>);//render () converts our ' virtual dom ' (see below) to a real DOM tree: LetDom= Render(Vdom);//Append the new nodes somewhere:Document.Body.appendchild(DOM);//Remember that "virtual DOM"? It ' s just json-each "Vnode" is a object with 3 properties. LetJson= JSON.stringify(Vdom, NULL, "');//The whole process (JSX, Vdom, DOM) in one step:Document.Body.appendchild(Render(<Pre ID="Vdom">{Json}</pre>));

Codependemo

Jsx what Ghost (together to write a jsx rendering engine)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.