One. What is JSX?

JSX syntax is similar to the following code:

const element = ( <div> <h1>Hello! </h1> <h2>Good to see you here.</h2> </div> );Copy the code

JSX is a core component of React. It uses XML tags to declare interfaces that can be nested within each other. JSX will eventually be compiled into JS.

Ii. JSX specific rules

  1. JSX itself is also an expression, which can be used as a return value of a function, which can be assigned to other variables, which can participate in if,for, and so on
  2. JSX does not need to be wrapped in single and double quotes, so perhaps the editor should have a JSX-compatible plug-in.
  3. JSX uses camelCase(small hump nomenclature). Some attribute names in native HTML have been changed, such as class to className, which needs special attention.
  4. The expression embedded in JSX can be any valid expression.
  5. Insert string literals in JSX need to be wrapped in double quotes, as in example 1; Insert the expression, as in example 2
Const element = <div tabIndex="0"></div>; Const element = <img SRC ={user.avatarurl}></img>;Copy the code
  1. JSX is best wrapped in a “()” to prevent auto-insert semicolon traps.

How does JSX render

The JSX statement (example 1) is used by React to generate a React element (Example 2), which is eventually called by React.createElement() (example 3) to build the DOM tree.

// Example 1 const element = (<h1 className="greeting"> Hello, world! </h1> );Copy the code
Const element = {type: 'h1', props: {className: 'greeting', children: 'Hello, world! '}};Copy the code
// Example 3 const element = React. CreateElement ('h1', {className: 'greeting'}, 'Hello, world! ');Copy the code

What are the advantages of JSX

  1. Declarative syntax makes building pages more intuitive.

What are the disadvantages of JSX

Why use JSX

  1. React believes that rendering logic is essentially coupled with logic and UI, so JSX is convenient for coupling logic and UI to a certain extent.
  2. Maybe it’s easier to write React using JSX