This is the 18th day of my participation in the August Challenge

preface

JSX is a syntax for describing HTML in JavaScript, although the semantics of the transformation are implementation-dependent. JSX is itself an expression, and when compiled, the JSX expression becomes a normal JavaScript object. JSX is popular with the React framework, but other implementations exist. TypeScript supports embedding, type checking, and compiling TSX directly into JavaScript.

A preliminary study

Students who have written React should be familiar with JSX, and the relationship between TSX and JSX is just like JS and TS. As long as we understand JSX, TSX will be easy.

import React from 'react'

function render(props) {
    return <div>{props.title}</div>
}
Copy the code

After compiling, it will become the following js code that the browser can execute directly

import React from 'react'

function render(props) {
    return React.createElement('div'.null, props.title)
}
Copy the code

In essence, TSX provides a method for creating React elements (React. CreateElement (Component, props,… Children) is syntactic sugar.

The as operator

Recall how to write type assertions:

var foo = <foo>bar;
Copy the code

But in TSX, <> is considered to be an HTML description and there are syntactic conflicts, so we need to change it to something like this:

var foo = bar as foo;
Copy the code

Type checking

For a TSX expression, the type returned is dependent on the input. This is essentially the return value of React. CreateElement. For React, the inherent element generates a string (react.createElement (“div”)), whereas your custom component does not (react.createElement (MyComponent)).

// Return the native DOM type
function render() {
    return <div></div>
}

// Return the Car type
function render() {
    return <Car />
}

// Returns a string
function render() {
    return 'xxx'}...Copy the code

expression

In Vue, there are expressions such as V-if and V-for to describe business logic, while in TSX, the native capabilities of JS can be called directly.

In TSX, common expressions are as follows:

  • The variable name.
  • Function definition expression;
  • Attribute access expression;
  • Function call expression;
  • Arithmetic expression;
  • Relational expression;
  • Logical expression;
function render(props) {
    if (props.dataList.length === 0) {
        return null;
    }
    return (
        <div>
            {props.dataList.map(item => <Item>{item}</Item>)}
        </div>)}Copy the code

summary

The use of JSX in React brings us great convenience, while TSX makes up for JSX’s lack of type system and type verification, greatly reducing the probability of errors in our code.