23 [React Basics-2] JSX

Write in front

This article is the second article in the [React Basics] series. In this article, we introduce an alternative coding method in React-JSX. It allows us to write HTML tags directly in the JS code. If you are interested, let's learn together.

Overview

At the end of the last article, you will definitely have a lot of questions. From the beginning of this article, we will start to answer these questions one by one. This article first answers the first question: Why can HTML tag code be written in the js suffix code file, and the code will not report an error?

Project demo address

https://github.com/xuqwCloud/reactbasic

Introduction to JSX

JSX is not a new programming language or a new technology, as long as you know JS and HTML, then you will be JSX, because JSX is actually just syntactic sugar for JS code.

React allows us to mix HTML and JS code to write. For example, the following code you see can run successfully and have a return value:

import React from 'react';
import ReactDOM from 'react-dom';

let element = <h1>JSX Hello World</h1>;

ReactDOM.render(element, document.getElementById('root'));

In the above code, we assigned a piece of HTML tag code to an element variable, and finally passed this variable as a parameter to ReactDOM's render() method. At this time, we can see the normal page display on the browser page, as follows:

If you haven't touched react before, you will be surprised when you see this code for the first time, thinking: This must be a mistake, how can this code run. But this kind of code is everywhere in the react project, and they can run normally, because this is a kind of syntactic sugar that react provides to us to write code. With this coding method, our program development efficiency will be greatly improved. , If you use JSX for a long time, I believe you will love it.

So why did React come up with such a thing for no reason? Is it not good to use traditional HTML files, JS files, and CSS files to jointly develop a page? This is because react believes that in our development process, the rendering logic is actually intrinsically coupled to the UI logic. For example, we need to bind mouse click events in some UIs, and if some data changes, we need to render new data to UI, display the data returned by the background request in the UI, etc. These operations are actually not suitable for the traditional development method of purely writing UI in HTML files, and purely writing interactive logic in JS files. React directly uses traditional development methods. The model has been subverted. It does not allow us developers to artificially separate HTML, JS, and CSS, but to store HTML and JS together in a unit logic, and call this unit logic "component" .

So in the development of react, we are actually developing individual components. By combining these components in different ways, we can realize a complete page system. Then you may ask, I directly mix HTML code and JS code together to write, how is it distinguished when the code is executed? This is actually what React is doing. It will parse the JSX code we have written. Friends who are interested in this process can pay attention to the blogger’s later React source code interpretation article, which will introduce in detail. This article only needs to know. It is legal for us to write JSX code in React.

Expressions in JSX

When writing JSX code, we can put any valid JavaScript expression in braces, such as the following code:

import React from 'react';
import ReactDOM from 'react-dom';

// JSX表达式 变量
let name = 'xbeichenbei.com';

// JSX表达式 函数
function getName() {
    return 'X北辰北';
}

let element = (
    <h1>
        {getName()}的网站域名是{name},建站已经{1 + 2}年了!
    </h1>
);

ReactDOM.render(element, document.getElementById('root'));

Specific attributes in JSX

When writing JSX code, the attributes of our HTML tag elements can be specified in the form of quotation marks or braces, such as the following:

let classTest = 'view';

let element = (
    <h1 id="xbeichenbei" className={classTest}>
        指定标签属性
    </h1>
);

ReactDOM.render(element, document.getElementById('root'));

In the above code, we specify the id and class attributes for the h1 element. The former attribute value is in the form of a string that we are familiar with before, the latter attribute value is specified by braces, and the latter’s class attribute name is used ClassName is not used. This is because the coding method of JSX is closer to JS, but these names of class are keywords in JS, so React uses the form of small camel case when specifying element attribute names, and does not use HTML The default attribute name, everyone must pay attention to when writing code.

How does JSX execute

In the bottom layer of our react project application, there is actually a tool for converting JSX code into normal JS code, and its name is "Babel". Babel will translate JSX into a function call called React.createElement().

So the following two sample codes are completely equivalent:

//JSX形式的代码
const element = (
  <h1 className="greeting">
    Hello, world!
  </h1>
);


//JS形式的代码
const element = React.createElement(
  'h1',
  {className: 'greeting'},
  'Hello, world!'
);

React.createElement()Some checks are performed in advance to help us write error-free code, but in fact it creates an object like this:

//这是简化过的结构
const element = {
  type: 'h1',
  props: {
    className: 'greeting',
    children: 'Hello, world!'
  }
};

These objects are called "React elements". They describe what we want to see on the screen. React reads these objects and uses them to build the DOM and keep it updated.

other

In our above code, we all assign an HTML tag element to a variable. What if we assign a DOM node containing child nodes to a variable? It's actually very simple, just wrap this HTML node with a bracket when assigning, as follows:

let element = (
    <div>
        <span>子节点1</span>
        <img src="img.png" />
    </div>
);

When we write front-end code, everyone will definitely consider XSS attacks in terms of security, but when writing JSX in React, you don’t have to worry too much, because the component code written by JSX is compiled before rendering, so in our There will never be content in the app that you did not write explicitly.

to sum up

The above is a brief introduction to JSX. In this article, you only need to know how to write the JSX code, and understand the wording of braces and the partial changes of the attribute names of elements. You don't need to pay more attention to the others.

Guess you like

Origin blog.csdn.net/qq_35117024/article/details/109090153