【React】JSX syntax

I. Introduction

This blog post will explain an interesting tag syntax, which is neither a string nor HTML . It is called JSX and is a JavaScript syntax extension. It is recommended to use JSX with React . JSX can well describe how the UI should be presented. It should have an interactive nature. JSX may be reminiscent of a templating language, but it has the full power of JavaScript

Note: Although JSX is a JavaScript syntax extension, you can find that it cannot be used directly in HTML . You need to use Babel for conversion. After conversion, it will automatically parse it into the desired style for us.

2. Introduction to JSX

JSX directly integrates HTML syntax into JavaScript code, and then converts it into pure JavaScript through a translator and then executes it by the browser. In actual development, JSX has been programmed into pure JavaScript during the product packaging stage , without any side effects. On the contrary, it will make the code more intuitive and easier to maintain. The compilation process is implemented by Babel 's JSX compiler.

3. JSX principles

To understand the principles of JSX, you need to first understand how to use JavaScript objects to represent the structure of a DOM element.

1. DOM structure example

<div class='app' id='appRoot'>
  <h1 class='title'>欢迎进入React的世界</h1>
	<p>React.js是一个帮助你构建页面UI的JavaScript库</P>
</div>

All the information in the above HTML can be represented by JavaScript objects:

{
    
    
  tag:'div',
  attrs:{
    
    className:'app',id:'appRoot'},
  children:[
    {
    
    
      tag:'h1',
      attrs:{
    
    className:'title'},
      children:['欢迎进入React的世界']
    }{
    
    
      tag:'p',
      attrs:null,
      children:['React.js是一个帮助你构建页面UI的JavaScript库']
    }
  ]
}

However, it is too long to write in JavaScript and the structure does not look clear. It is much more convenient to write in HTML. So React.js expanded the syntax of JavaScript so that the JavaScript language could support syntax similar to HTML tag structures written directly in JavaScript code, which makes writing much more convenient. The compilation process converts HTML-like JSX structures into JavaScript object structures

2. Example of JSX structure of HTML

import React from 'react'

class App extends React.Component {
    
    
    render() {
    
    
        return (
            <div class='app' id='appRoot'>
                <h1 class='title'>欢迎进入React的世界</h1>
                <p>React.js是一个帮助你构建页面UI的JavaScript库</p>
            </div>
        )
    }
}

export default App
//从react的包当中引入了React。只要你要写React.js组件就必须引入React,因为react里有一种语法叫JSX
import React from 'react'
//ReactDOM可以帮助我们把React组件渲染到页面上去
import ReactDOM from 'react-dom'
import App from './component/classComponent'

//ReactDOM里有一个render方法,就是把组件渲染并且构造DOM树,然后插入到页面上某个特定的元素上
ReactDOM.render(<App/>,document.getElementById("root")
)

3. Code after compilation

import React from 'react'

class App extends React.Component {
    
    
    render() {
    
    
        return (
            React.createElement(
                "div",
                {
    
    
                    className: 'app',
                    id: 'appRoot'
                },
            ),
            React.createElement(
                "h1",
                {
    
    
                    className: 'title',
                },
                "欢迎进入React的世界"

            ), React.createElement(
                "p",
                null,
                "React.js是一个构建页面UI的JavaScript库"
            )
        )
    }
}

export default App
//从react的包当中引入了React。只要你要写React.js组件就必须引入React,因为react里有一种语法叫JSX
import React from 'react'
//ReactDOM可以帮助我们把React组件渲染到页面上去
import ReactDOM from 'react-dom'
import App from './component/classComponent'

//ReactDOM里有一个render方法,就是把组件渲染并且构造DOM树,然后插入到页面上某个特定的元素上
ReactDOM.render(React.createElement(App),document.getElementById("root")
)

React.createElement will construct a JavaScript object to describe your HTML structure information, including tag names, attributes, sub-elements, etc. The syntax is:

React.createElement(
  type,
  [props],
  [...children]
)

The so-called JSX is actually a JavaScript object, so when using React and JSX, you must go through the compilation process.

JSX uses react to construct the component, compile it with babel -> JavaScript object - ReactDOM.render() -> DOM element -> insert into the page

4. Why use JSX

1. Characteristics of JSX

  1. React believes that rendering logic is intrinsically coupled with other UI logic. For example, the UI needs to be bound to handle events, the UI needs to be notified when the state changes at certain moments, and the prepared data needs to be displayed in the UI.
  2. React does not artificially separate markup and logic into different files. Instead, it achieves separation of concerns by storing both in loosely coupled units called "components."
  3. React does not mandate the use of JSX, but most people find it visually helpful when putting JSX and UI together in JavaScript code. It also enables React to display more useful error and warning messages

2. JSX writing specifications

  • The top level of JSX can only have one root element , so we often wrap a div in the outer layer .
  • In order to facilitate reading, we usually wrap a parentheses () in the outer layer of JSX, which makes it easier to read, and JSX can be written with line breaks.
  • Tags in JSX can be single tags or double tags

Note: If it is a single tag, it mustend with />

5. Use of JSX

1. Embed JS expressions

JavaScript expression

let content = '插入的内容' //存储在js中的数据
let h1 = ( <h1>{
    
    content}</h1> )

JS expressions such as a, a+b, functionName(param) function call expression, array.map() function, function test ()
{} definition function, etc. can be received by a variable. You can also write { console.log(1) }

//array.map()是有返回值的
let arr = [1,2,3,4]
let result = arr.map((num) => {
    
    
    return num+1
})
console.log(result) //[2,3,4,5]
//定义函数,其本身也是返回值
const x = function test(){
    
    
    console.log('1')
}

console.log(x)
/* 这个函数本身
test(){
    console.log('1')
}
*/
  • As long as it is a legal js expression (such as various data types), it can be embedded
  • JSX itself is also a js expression
  • Objects in js cannot be embedded and generally only appear in the style attribute
import React from 'react'
import ReactDOM from 'react-dom'

// 函数调用表达式
const sayHi = () => 'Hi~' //函数调用后返回字符串Hi~

const dv = <div>我是一个div</div> //dv是JSX

const title = (
  <h1>
    <p>{
    
    1}</p>
    <p>{
    
    'a'}</p>
    <p>{
    
    1 + 7}</p>
    <p>{
    
    3 > 5 ? '大于' : '小于等于'}</p>
    <p>{
    
    sayHi()}</p>
    {
    
    dv} {
    
    /*JSX自身也是js表达式,也可以嵌入到JSX中*/}

    {
    
    /* 以下为错误演示:
    注意——注释是js中的,嵌入到jsx中的注释也需要用花括号括起来 */}
    {
    
    /* <p>{ {a: '6'} }</p> 花括号里一般不写对象,除非在style属性中*/}
    {
    
    /* { if (true) {} } 花括号中不能出现语句 */}
    {
    
    /* { for (var i = 0; i < 10; i++) {} } 花括号中不能出现语句*/}
  </h1>
)

// 渲染
ReactDOM.render(title, document.getElementById('root'))

2. Conditional rendering

Use if/else or ternary operator or logical AND operator to implement

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

const isLoading = false

// if-else
// const loadData = () => {
    
    
//   if (isLoading) {
    
    
//     return <div>loading...</div>
//   }
//   return <div>数据加载完成,此处显示加载后的数据</div>
// }

// 三元表达式:
// const loadData = () => {
    
    
//   return isLoading ? (<div>loading...</div>) : (<div>数据加载完成,此处显示加载后的数据</div>)
// }

// 逻辑与运算符:
const loadData = () => {
    
    
  return isLoading && (<div>loading...</div>)
}

const title = (
  <h1>
    条件渲染:
    {
    
    loadData()}  {
    
    /*把函数调用的返回值嵌入JSX*/}
  </h1>
)
ReactDOM.render(title, document.getElementById('root'))

3. List rendering

Use the map () method of the array to return a new array. The elements in the array are the values ​​of the original array elements after calling the function in sequence.

①、arr.map()

  • When rendering the list, you need to add the key attribute. The value of the key attribute must be unique.
  • Map() adds key attributes to whomever iterates through.
  • Try to avoid using (changeable) index numbers as keys, such as the second parameter index of map. It is not recommended to use it as the key value.
//数组可以作为 react的合法节点进行遍历,所以下例不报错。但对象不能
let arr = [<li>aaa</li>, <li>bbb</li>]
const list = (
  <ul>
      {
    
    arr}
  </ul>
)

The original pure data ['aaa', 'bbb'] can be processed into labeled data, which is equivalent to:

//增加一个id属性作为key值
let arr = [{
    
    
    id:1,
    name:'aaa'
},{
    
    
    id:2,
    name:'bbb'
}]
//创建虚拟DOM
const list = (
  <ul>
    {
    
    arr.map(item => <li key={
    
    item.id}> {
    
    item.name} </li>)}
  </ul>
)
//渲染虚拟DOM
ReactDOM.render(list,document.getElementById('root'))

6. Components

1. Class components

The addition of ES6 allows JavaScript to directly support the use of class to define a class. The way react creates components is to inherit the class used. ES6 class is the currently officially recommended way of use. It uses ES6 standard syntax to build

import React from 'react'

class App extends React.Component {
    
    
    render() {
    
    
        return (
            <div>hellow react Component</div>
        )
    }
}

export default App;
//从react的包当中引入了React。只要你要写React.js组件就必须引入React,因为react里有一种语法叫JSX
import React from 'react'
//ReactDOM可以帮助我们把React组件渲染到页面上去
import ReactDOM from 'react-dom'
import App from './component/classComponent'

//ReactDOM里有一个render方法,就是把组件渲染并且构造DOM树,然后插入到页面上某个特定的元素上
ReactDOM.render(<App/>,document.getElementById("root")
)

①. Instantiate components

The ES6 class component is actually a constructor. Every time you use the component, it is equivalent to instantiating the component.

import React from 'react'

class App extends React.Component {
    
    
    render() {
    
    
        return (
            <div>hellow react Component</div>
        )
    }
}

const app = new App({
    
    
  name:'react'
}).render()

export default App;
//从react的包当中引入了React。只要你要写React.js组件就必须引入React,因为react里有一种语法叫JSX
import React from 'react'
//ReactDOM可以帮助我们把React组件渲染到页面上去
import ReactDOM from 'react-dom'
import App from './component/classComponent'

//ReactDOM里有一个render方法,就是把组件渲染并且构造DOM树,然后插入到页面上某个特定的元素上
ReactDOM.render(app,document.getElementById("root")
)

2. Function components

function App(){
    
    
    return(
        <div>hello functional component</div>
    )
}
export default App
import React from 'react'
import ReactDOM from 'react-dom'
import App from './component/functionComponent'

ReactDOM.render(
    <App />,
    document.getElementById("root")
)

3. Component style

①. Inline style

If you want to add inline styles to the virtual DOM, you need to use an expression to pass in the style object:

<div style={
    
    {
    
    backgroundColor:"red",fontSize:"13px"}}>Hello World</div>

Inline styles require writing a style object, and the location of this style object can be placed in many places. For example: in the render function, on the component prototype, in the external link js file

import React, {
    
     Component } from 'react'

export default class nestComponent extends Component {
    
    
  render() {
    
    
    var objStyle = {
    
    
      backgroundColor: "pink",
      fontSize: "15px"
    }
    return (
      <div>
        <div style={
    
    objStyle}>nestComponent</div>
        <div style={
    
    {
    
    backgroundColor:"purple"}}>Hello World</div>
      </div>
    )
  }
}

Insert image description here

②. Use class

React recommends that we use inline styles because React considers each component to be an independent whole.
In fact, in most cases we still add a lot of class names to elements, but it should be noted that class requires Ctrip className (because after all, we are writing JS-like code, we will receive the existence of JS rules, and the class keyword)
Insert image description here
Insert image description here
Insert image description here

7. Summary

In fact, JSX is just syntactic sugar for the React.createElement(component, props, ...children) function. All JSX will eventually be converted into React.createElement function calls. If you want to learn more about the implementation principles of JSX, please see In-depth JSX

Guess you like

Origin blog.csdn.net/weixin_45490023/article/details/133266585