JSX stands for javascript XML, a way to write HTML structures in javascript code.
Advantages
Uses HTML-like syntax.
Leverage js’ own programmability to create HTML structures.
Usage
Basic instructions
You need to use babel for syntax conversion, and for react the following code is equivalent.
Expressions
Expressions can be used in JSX. Expressions use a pair of brackets to mark the expression.
As you can see from the above example, JSX expressions support the following.
- recognition of regular variables
- native js method calls
- ternary operators
Statements such as if/switch/variable declarations are not available in JSX, they are not expressions and are not supported in jsx.
List rendering
In vue, we can use v-for to iterate over a list data and can implement repeated element generation in templates. You can do the same thing in angular using *ngFor
, and we can do the same thing in JSX.
You can use the map method to return an expression containing jsx
Since the elements are rendered repeatedly, you need to assign a key to the generated elements, otherwise it will affect the performance of the virtual dom.
The key can only use the number/string type, and the key attribute will not appear on the real dom attribute, and is used internally.
Conditional rendering
JSX supports the generation of HTML structures that satisfy conditions, which can be implemented using the ternary operator
.
Style handling
JSX supports css style handling
-
in-line styles - style - bind style attributes to element properties
-
in-line styles - style - better writing
-
class name style - ties a className attribute to the element
In the first example, since the style attribute requires an object, the first level
{}
is an expression and the second level{}
is the object definition bracket, so it is usually written as Object, which is also more convenient to control.
Dynamic class name control
In the above example, we have used the class name style in css to set the style, but sometimes we want to control the style of an element in some scenarios, it will change, this time we need to use dynamic class name control.
Precautions
JSX considerations for practical applications
- JSX must have a root node, meaning that React cannot use jsx to create the top-level html element; we must first provide an empty element as the root node for React. (or created using the ghost node
<></>
). - All tags must form closures, either pairwise or self-closing.
- The syntax in JSX is closer to that of javascript, with small-hump naming convention for attributes
class -> className
for -> htmlFor
. - JSX supports multiple lines (line breaks) and can be wrapped with
()
if a line break is needed.