JSX, or Javscript XML, is a set of XML syntax defined within JS. Currently, the compiler uses Babel as the JSX. This is why the Babel was loaded in previous installments.
Facebook introduced JSX to address the complexities of front-end code engineering and maintenance difficulties. JSX provides us with a way to implement virtual DOM. By using the JSX of the class XML syntax, the virtual DOM is defined to reduce the operation of the real DOM, thus improving operational efficiency. Because of the use of JSX, creating components in the react project becomes fairly straightforward, and users can mix program logic (programming logic) and Markup Language (markup) to facilitate readability and predictability of the code. Effectively improve the maintenance efficiency of the code.
Next we talk about the basic syntax of JSX:
1. JSX Basic definition
const element =
From the above code, we can understand that the JSX XML syntax is equivalent to a JS expression, which can be directly assigned to the variable. (actually not so, really understand "look here")
2. Define expressions in Jsxfunction formatName(user) { return user.firstName + ' ' + user.lastName;}const user = { firstName: 'Harper', lastName: 'Perez'};const element = (
Inside the JSX, we can execute the method (function) and enter the object. You can output string variables directly, and so on. This is {}
similar to the syntax in PHP <?php ?>
.
3. Jsx defined attribute (Attribute)const element = <div class="div-test"></div>const element = <div className="div-test"></div>
The JSX attribute definition follows the CamelCase principle. If you define the default properties for HTML tags, you can use the rules for HTML. In this example, both lines of code are used to define the properties of the class.
// 这两行的代码效果相同const element = <div tabIndex="0"></div>;const element = <div tabindex="0"></div>;
This example defines a property name named TabIndex, followed by the use of the CamelCase format in JSX. Of course, if you do not use it, react can still execute.
const element = <a href={person.link}> </a>
Similarly, a variable expression can be added to an attribute {}
to execute it.
4. JSX Embedded Sub-tagsconst element = ( <div>
In this case, it must be used ()
to represent. At the same time, there can be only one root node in JSX. Cannot have two nodes in parallel, as follows:
const element = (
In this case, react is unable to compile successfully.
5. Summary
- JSX is an XML syntax within JS that displays the program logic and markup language in the same file. In favor of code development and maintenance
- In Jsx, we introduced the concept of virtual dom "look here"
- JSX's basic syntax is quite flexible, can be embedded in expressions, define attributes, etc.
Five minutes to learn react (iv): What is JSX