JSX core syntax

1. 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).

React argues that rendering logic is intrinsically coupled to other UI logic

  • For example, the UI needs to bind events (buttons, A native, etc.);
  • For example, the UI needs to display data state, and when some state changes, the UI needs to be changed.
  • They are inseparable, so React doesn’t talk about separating tags into different files. Instead, it groups them together.
  • All we need to know here is that JSX is actually a structural syntax embedded in JavaScript;

2.JSX writing specification

  • JSX can only have one root element at the top level, and we often wrap a div around the top layer.
  • 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;
  • Labels in JSX can be single or double labels (if single, they must end with />)

3. Comments in JSX

Single-line comments and multi-line comments need to be written in curly braces {}

{
    // I'm a one-line comment
}
{/* I am a comment */}
Copy the code

4. Embed variables in JSX

  • If the variable is Number, String, or Array, it can be displayed directly.
  • When a variable is null, undefined, or Boolean, the content is empty (if you want to display it, you can convert it to a string for display).
  • Object types cannot be embedded as variables (‘not valid as a React child’)
 {
          // 1. The displayed content can be displayed normally in {}
          name: "lanzhou".// String
          age: 20.// Number
          names: ["abc"."cba"."nba"].// Array

          // 2. Cannot be displayed in {} (ignore)
          test1: null.// null
          test2: undefined.// undefined
          test3: true.// Boolean

          // 3. Objects cannot be subclasses of JSX
          friend: {
            name: "lanzhou".age: 20}}Copy the code

5.JSX embedded expression

  • Operational expression
  • Ternary operator
  • Execute a function
 render() {
        const {firstName, lastName, isLogin} = this.state;
        return (
          <div>{/*1. Operator expression */}<h2>{ firstName + " " + lastName }</h2>
            <h2>20 * 50 {}</h2>{/*2.<h2>{ isLogin ? "Welcome back ~":" Please login ~"}</h2>{/*3. Make a function call */}<h2>{this.sayHello()}</h2>
          </div>)}Copy the code

6.JSX binding properties

  • JSX binds common properties
  • JSX binding class
  • JSX binding style
 render() {
        const { title, imgUrl, link, active } = this.state;
        return (
          <div>{/* 1. Bind common attributes */}<h2 title={title}>I am heading</h2>
            <img src={getSizeImage(imgUrl, 140)} alt=""/>
            <a href={link} target="_blank">The baidu</a>{/* 2. Bind class */}<div className="box title">I'm a div element</div>
            <div className={"box title"+ (active ? "active":"")} >I'm also a div element</div>{/* 3. Bind style */}<div style={{color: "red", fontSize: "50px}} ">I'm div, bound to the style property</div>
          </div>
      )
Copy the code

7.JSX binding events

  • Binding events in JSX is similar to binding events in HTML native, but in React events are named in camelCase instead of pure lowercase.
  • However, we’ll notice that calling this in our bind callback event will be undefined. This is because the React callback function is called for us internally. React does not specify this, so callback.apply(undefined,[]) is used. But the only thing we usually need to access is our React component object. There are three solutions:
 increment = () = > {
     console.log(this);
  }
render() {
        return (
          <div>{/* 1. Bind this */}<button onClick={this.btnClick.bind(this)}>Button 1</button>
            <button onClick={this.btnClick.bind(this)}>Button 2</button>
            <button onClick={this.btnClick.bind(this)}>Button 3</button>{/* 2. Plan 2: Use the arrow function */}<button onClick={this.increment}>+ 1</button>{/* 2. Solution 3 (recommended): Pass in an arrow function directly and call the function that needs to be executed */}<button onClick={()= > { this.decrement(666) }}>-1</button>
          </div>)}Copy the code
  • For the transmission of binding event parameters, we recommend the third scheme binding this, which not only facilitates the transmission of parameters we want to pass, but also easily obtains the event object
  render() {
        return (
          <div>
            <ul>
              {
                this.state.movies.map((item, index, arr) => {
                  return (
                    <li className="item" 
                        onClick={ e= > { this.liClick(item, index, e) }}
                        title="li">
                      {item}
                    </li>)})}</ul>
          </div>)}Copy the code

JSX conditional rendering

In some cases, the page will display different content based on different conditions, or decide whether to render a portion of the content. Vue provides the corresponding v-if and v-show commands, but React implements conditional rendering.

  1. Conditional statement
  2. Ternary operator
  3. The and operator &&
  4. V-show effect (mainly controls whether the display attribute of the HTML tag is None)
render() {
        const { isLogin } = this.state;

        // 1. If there is a lot of logical code in the case
        let welcome = null;
        let btnText = null;
        if (isLogin) {
          welcome = <h2>Welcome back ~</h2>
          btnText = "Quit";
        } else {
          welcome = <h2>Please log in ~ first</h2>
          btnText = "Login";
        }

        return (
          <div>{welcome} {/* 2.<button onClick={e= >this.loginClick()}>{isLogin ? "Exit" : "login "}</button>
            <h2>{isLogin ? "Hello, 666": null}</h2>{/ * 3. The solution 3: logic and && * /} {/ * logic with: a condition is not established, the condition will not judge the * /}<h2>{ isLogin && "你好啊, 666" }</h2>
            { isLogin && <h2>Hello, 666</h2> }
          </div>)}Copy the code
{/* 4. Scheme 4: Dynamically change the display attribute of the corresponding label to block or None */}
 render() {
        const { isLogin} = this.state;
        const titleDisplayValue = isLogin ? "block": "none";
        return (
          <div>
            <button onClick={e= >this.loginClick()}>{isLogin ? "Exit ":" login "}</button>
            <h2 style={{display: titleDisplayValue}} >Hello, 666</h2>
          </div>)}loginClick() {
         this.setState({
           isLogin:!this.state.isLogin
         })
       }
     }
Copy the code

9.JSX list rendering

In React, list generation and display are mostly used in JS higher-order functions. Of course, we can also use the for loop to generate and display lists.

render() {
        return (
          <div>
            <h2>The name list</h2>
            <ul>
              {
                this.state.names.map(item => {
                  return <li>{item}</li>})}</ul>

            <h2>List of numbers (Filter 1)</h2>
            <ul>
              {
                this.state.numbers.filter(item => {
                  return item >= 50;
                }).map(item => {
                  return <li>{item}</li>})}</ul>

            <h2>List of numbers (Filter 2)</h2>
            <ul>
              {
                this.state.numbers.filter(item => item >= 50).map(item => <li>{item}</li>)}</ul>

            <h2>List of numbers (intercept)</h2>
            <ul>
              {
                this.state.numbers.slice(0, 4).map(item => {
                  return <li>{item}</li>})}</ul>
          </div>)}Copy the code

Ii. Brief Analysis of the nature of JSX

JSX is really just syntactic sugar for the react. createElement(type, config, children) method, which takes three arguments:

  1. Type, the type of the current ReactElement, is a string representing “div” if it is a tag element, or the component name if it is a component element.
  2. Config, the properties we bind in JSX will exist as key-value pairs in the Config object.
  3. Children, which holds the contents of the tag as an array of children

We know that JSX is parsed through Babel. We need to rely on Babel to write JSX. Pres…

If we write the code directly with react.createElement (), we don’t need bable to parse and render normally

The ReactElement () method returns a ReactElement object. What does the ReactElement object do? React uses the ReactElement object to form a tree of JavaScript objects. This tree is a concept we often talk about — the virtual DOM. We can print the result of JSX to see the corresponding ReactElemnt object:

The react.createElement () method calls the ReactElement object tree (DOM tree). The react.createElement () method calls the ReactElement object tree. The corresponding ReactElement object tree is converted to the real DOM by the reactdom.render () method for rendering in our browser.

Graph TD JSX --> ReactElement --> real DOM

Why the virtual DOM?

  • It is difficult to track state changes: in the original development mode, it is difficult for us to track state changes, which is not convenient for debugging of our application;
  • Low performance for manipulating the real DOM: Traditional development models tend to do a lot of DOM manipulation, which is very low performance;

DOM manipulation is performance-intensive:

  • Document.createelement creates a very complex object developer.mozilla.org/zh-CN/docs/…
  • DOM manipulation can cause backflow and redrawing of the browser, so frequent DOM manipulation should be avoided in development