This is the second day of my participation in the August More Text Challenge
preface
(,, · ∀ ·) Blue hello, this is my first in-depth learning and analysis of React. It’s a long road, and it’s still no return. Keep going. This article introduces the definition of JSX, the instructions to use it, and the principles behind it.
3 “big questions” about JSX
- What is the nature of JSX and how does it relate to JS?
- Why JSX? What are the consequences of not using it?
- What is the functional module behind JSX, and what does this functional module do?
What is the nature of JSX
React:
JSX is a syntactic extension of JavaScript that is close to the template language, but has full JavaScript capabilities.
How does JSX syntax work in JavaScript
React:
JSX will compile to react.createElement (), and react.createElement () will return a JS object called “React Element”.
Compiling is done by Babel.
Babel is a toolchain for converting ECMAScript 2015+ version code into backwardly compatible JavaScript syntax so it can run in current and older versions of browsers or other environments.
Here is an example of Babel compiling JSX:
As you can see, all JSX tags are converted to the React.createElement call. So JSX is essentially a syntactic sugar for JavaScript calls like React. CreateElement, which perfectly matches the React official statement that JSX has JavaScript capabilities.
Conclusion:
JSX compiles with Babel (with the same effect as react.createElement ()) to generate a “React Element” JS object that works in JavaScript.
Why JSX
Take a look at an example of Babel compiling JSX:
The JSX code is on the left and the react.createElement call is on the right.
You will find that JSX code is hierarchical and nested in a way that is consistent with actual functionality. The React.createElement code, on the other hand, is a very confusing mix that is not only unfriendly to read but also hard to write.
JSX syntactic sugar allows front-end developers to create virtual DOM using htML-like tag syntax that we are most familiar with, reducing learning costs while improving r&d efficiency and experience. This is why JSX is used.
What is the functional module behind JSX, and what does this functional module do
React.createElement, ReactElement, and reactdom. render are important functional modules supporting JSX.
- JSX is the syntactic sugar for react.createElement ().
- ReactElement is a virtual DOM that structures the data from createElement.
- ReactDOM. Render simply mounts all the ReactElement onto a real DOM container.