Notes arrangement of React beginner study -- Introduction and syntax of JSX

Let's look at this code first:

import React from 'react';
//In the final rendering, you need to call the react DOM library to render jsx to all pages
import ReactDOM from 'react-dom';
import * as serviceWorker from './serviceWorker';

let h = <React.Fragment>
    <h2>hello</h2>
    <ul></ul>
    </React.Fragment>

//Render the structure of the first parameter to the root tag
ReactDOM.render(h, document.getElementById('root'));

serviceWorker.unregister();

Analysis:

1. The full name of JSX is JavaScript XML. Writing XML tags in js is an extension syntax of JavaScript. JSX tag syntax is neither string nor HTML. After compilation, JSX will actually be converted into ordinary JavaScript objects to describe the UI information to be displayed.
The compilation process of JSX is shown as follows:

2. jsx syntax
1) JSX can be assigned to variables as values

let h =(
    <div>
        <h2>hello</h2>
        <span>React</span>
    </div>
);
ReactDOM.render(h, document.getElementById('root'));

2) it can be used as the return value of a function

function createH(){
    return <React.Fragment>
        <h2>hello</h2>
        <ul></ul>
    </React.Fragment>
}
ReactDOM.render(createH(), document.getElementById('root'));

3) can also exist in the array

let arr = [
    <h2 key="111">hello</h2>,
    <ul key="222"></ul>,
]
ReactDOM.render(arr, document.getElementById('root'));

If no key is written in the array, the console will output the following warning information:

4) JavaScript expressions used in JSX should be included in braces. Put a parenthesis outside the JSX code to prevent the semicolon from automatically inserting.

function formatName(user) {
    return user.name + ' ' + user.date;
}
const user = {
    name:'kristy',
    date:'2018-12-18'
};
let value  = 'hello';
let h = (
    <div>
        <h2>{value}</h2>
        <span>{formatName(user)}</span>
    </div>
);

Other detailed introduction: https://react.docschina.org/docs/introducing-jsx.html

Keywords: Javascript React Fragment xml

Added by ihcra on Tue, 03 Dec 2019 03:34:20 +0200