JSX profile

The sample

// This is JSX syntax, so you can assign an HTML snippet to a variable
// You can think of the HTML fragment as a value,
// It will be converted to VDOM and rendered as a real DOM on the page
const res = <h2>Hello World</h2>

ReactDOM.render(res, document.getElementById('app'))
Copy the code

1.1 2 prerequisites for JSX

  1. Using thebabelCompile and convert
  2. inscriptUse is declared onbabelTo compiletype='text/babel'

1.2 What is JSX

  • JSX is a JavaScript syntax eXtension, also known in many places as JavaScript XML because it looks like an XML syntax;
  • It describes our UI interface, and its completion can be used in conjunction with JavaScript;
  • It is different from the module syntax in Vue. You do not need to learn the instructions in module syntax (such as V-for, V-if, V-else, V-bind).

1.3 Why use JSX

React’s design philosophy is different from that of other frameworks. For example, Vue uses Template, Script, and style to separate interface, style, and layout

However, the design philosophy in React is all in JS. In React, it believes that all content can be written in JS, and there is internal coupling between interface and layout and JS code, which is mainly manifested as

  1. For example, the UI needs to bind events (buttons, A native, etc.);
  2. For example, the UI needs to display data state, and when some state changes, the UI needs to be changed

So React doesn’t talk about separating tags into different files. Instead, it groups them together. This is called a Component.

All we need to know here is that JSX is actually a structural syntax embedded in JavaScript;

1.4 Some written specifications of JSX

  • The top layer of JSX can only have one root element, so we often wrap a native div or main tag around it (or use the Fragment we’ll learn about later).

  • For ease of reading, we usually wrap a parenthesis () around JSX so that it is easy to read and JSX can be written on a new line;

    • This parenthesis is not required, but there is a slight difference between parentheses and no parentheses
      • JSX can be wrapped in parentheses. If there are no parentheses, all JSX must be written on one line. An error is reported if the JSX is wrapped
      • Parentheses make code easier to read and maintain than without parentheses
  • In JSX, you can write a single tag or a double tag, but if you use a single tag, JSX uses strict syntax, that is, in JSX

    The single tag must be closed, for example

1.5 JSX comments

Comments in JS

// Inline comments
// ...

// block level comments
/ *... * /

// Multi-line comments
/ * * * * * /
Copy the code

Annotations in JSX

{/* I am a comment in JSX */}

{/* If you use // in JSX or use /**/ directlyThese comments will be output as text nodes */}Copy the code

When using JS annotations in JSX, they are output as text nodes

1.6 Using variables in JSX

Case 1: Number,String, and Array can be rendered normally

class App extends React.Component{
 constructor(str, num, arr) {
     super(a)this.state = {
         str: 'Klaus'.num: 23.arr: ['Klaus'.'Alice'.'Kobe']}}render(){{/* Destruct assignment */}
     const {str, num, arr} = this.state

     return (
         <div>
             <div>{ str }</div>
             <div>{ num }</div>{/* JSX will automatically fetch each element of the array and display */}<div>{ arr }</div>
         </div>
     )
 }
}

ReactDOM.render(<App />.document.getElementById('app'))
Copy the code

Case 2: Null, undefined, Boolean is not rendered on the page by React by default

class App extends React.Component{
 constructor() {
     super(a)this.state = {
         nullElem: null.undefinedElem: undefined.trueElem: true.falseElem: false}}render() {
     const {nullElem, undefinedElem, trueElem, falseElem} = this.state

     return (
         <div>
             <div>{ nullElem }</div>
             <div>{ undefinedElem }</div>
             <div>{ trueElem }</div>
             <div>{ falseElem }</div>
         </div>
     )
 }
}

ReactDOM.render(<App />.document.getElementById('app'))
Copy the code

Result: No output is displayed

React does not display null,undefined, Boolean values

render() {
 return (
     <div>{/* This is the traditional way to write */}<div>{ this.state.age > 18 ? 'OK' : '' }</div>{/* React */}<div>{ this.state.age > 18 ? 'OK' : null }</div>
         <div>{ this.state.age > 18 ? 'OK' : undefined }</div>{/* flag is a Boolean defined in state. If flag is true, this.state.name is output. If flag is false, false is output.<div>{ this.state.flag && this.state.name }</div>

     </div>)}Copy the code

Null, Boolean, undefined can be displayed on the page if desired

These will not display properly until they are converted to strings

The conversion mode is as follows:

  1. calltoStringMethod, only suitable forBoolean.Null, and undefinedThere is notoStringmethods
  2. callStringMethod,Null, undefined, BooleanAll can be called
  3. Simply add an empty string, for examplenull + ''.Null, undefined, BooleanAll can be called

Case 3: Object type not valid as a React child

class App extends React.Component{
 constructor() {
     super(a)this.state = {
         obj: {
             name: 'Klaus'.age: 23}}}render() {
     return (
         <div>
             <div>{ this.state.obj }</div>
         </div>
     )
 }
}

ReactDOM.render(<App />.document.getElementById('app'))
Copy the code

Results:

JSX will be subclassed as React, but the object cannot be subclassed as React

1.7 Using expressions in JSX

this.state = {
    firstName: 'Klaus'.lastName: 'Wang'.isLogin: true
}

render() {
    const {firstName, lastName, isLogin} = this.state

    return (
        <div>{/* JSX can use operator expressions */}<div>{ firstName + ' ' + lastName  }</div>
            <div>{10 + 4}</div>{/* JSX can use ternary expressions (ternary operators) */}<div>{ isLogin ? 'Welcome back' : 'Please log in first'}</div>{/* Other operators include logical and, logical or, map, filter, etc. */}</div>)}Copy the code
this.state = {
    firstName: 'Klaus'.lastName: 'Wang'
}

getFullName() {
    // Note: this is correct, not undefined by default
    return this.state.firstName + this.state.lastName
}

render() {
    return (
        <div>{/* This method is called by ourselves. This is not the same as the event callback which was called by React. } {this.getFullName()} */} {this.getFullName()}</div>)}Copy the code

React React JSX JSX JSX JSX JSX JSX JSX JSX JSX