Come and join us!

“The Newbies of Little Wo Shan” provides front-end developers with technical information and a series of basic articles. For a better user experience, please go to xhs-rookies.com/ to learn the latest articles.

“Code Tailor “, if you are interested in our article, or would like to make some suggestions, please follow the official account of “Rookie of Xiaohe Mountain” on wechat and contact us. You can also view our article on wechat. Every suggestion or approval is a great encouragement to us!

preface

It’s not a string or HTML. It’s called JSX, and it’s a syntax extension for JavaScript. We recommend using JSX in React.

This article introduces you to the following:

  • knowJSXThe grammar of the
  • inJSXEmbedded expression in
  • Event listeners
  • Conditions apply colours to a drawing
  • The list of rendering
  • JSXThe principle of analytic
  • Case practice

Know the syntax of JSX

What is JSX?

Let’s start with a piece of code:

const element = <h1>Hello, XHS-Rookies!</h1>
Copy the code

What is the tag syntax for the assignment to the right of the element declaration?

This interesting tag syntax is neither a string nor HTML.

It’s called JSX, and it’s a syntax extension to JavaScript. We recommend using JSX with React. JSX is a good way to describe how the UI should behave as it should interact. JSX may be reminiscent of a template language, but it has all the functionality of JavaScript.

Note: JSX is a JavaScript syntax extension, but you’ll notice that it doesn’t work directly in HTML. You’ll need Babel’s conversion, which will automatically parse it into the desired style.

Why use JSX?

React argues that rendering logic is intrinsically coupled to other UI logic, such as binding events in the UI, notifying the UI when state changes at certain moments, and displaying prepared data in the UI.

React does not use artificial separation of markup and logic into separate files. Instead, it separates concerns by storing both together in loosely coupled units called components.

React doesn’t 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.

JSX writing specification:

  • The top layer of JSX can only have one root element, so we often wrap a div primitive around it;

  • 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.

Note: If it is a single tag, it must end with />;

Embed expressions in JSX

If the content in JSX is dynamic, we can get it from an expression:

Writing rules: {expression}, the curly braces can be variables, strings, arrays, function calls and other arbitrary JS expressions;

Annotations in JSX

This is a syntax that is embedded in JavaScript, so when writing comments, you need to use JSX syntax:

<div>
  {/* I am a comment */}
  <h2>Hello World</h2>
</div>
Copy the code

JSX embedded variables

Case 1: If the variable is Number, String, or Array, it can be displayed directly

Case 2: When the variable is null, undefined, or Boolean, the content is empty.

  • If you want to displaynull,undefined,Boolean, then you need to convert it to a string; There are many ways to convert, for exampletoStringMethod, and empty string concatenation,String(variable);

Object type not valid as a React child

class App extends React.Component {
  render() {
    let data = {
      name: 'xhs-rookies'.age: 18.skills: ['JavaScript'.'React'.'Webpack'].test1: null.test2: undefined.flag: false.friend: {
        name: 'xhs-zymxxxs'.age: 29,}}return (
      <div>
        <div>{/* I am a comment */}<h2>Hello React</h2>
        </div>

        <div>{/* 1.<h2>{data.name}</h2>
          <h2>{data.age}</h2>
          <h2>{data.skills}</h2>{/* 2. Do not display */}<h2>{data.test1}</h2>
          <h2>{data.test1 + ''}</h2>
          <h2>{data.test2}</h2>
          <h2>{data.test2 + ''}</h2>
          <h2>{data.flag}</h2>
          <h2>{data.flag + ''}</h2>{/* 3. Do not display */}<h2>123{data.friend}</h2>
        </div>
      </div>
    )
  }
}

ReactDOM.render(<App />.document.getElementById('app'))
Copy the code

Why do null, undefined, and Boolean display empty content in JSX? The reason is that there is a lot of judgment in development;

  • Do not display a content when the result is false;
  • Display a content when the result is true;

JSX embedded expression

In JSX syntax, you can place any valid JavaScript expression inside curly braces. For example, 2 + 2, user.firstName, or formatName(user) are valid JavaScript expressions.

In the following example, we will call the result of the JavaScript function formatName(user) and embed the result in the

element.

function formatName(user) {
  return user.firstName + ' ' + user.lastName
}

const user = {
  firstName: 'xhs'.lastName: 'rookies',}const element = <h1>Hello, {formatName(user)}!</h1>

ReactDOM.render(element, document.getElementById('root'))
Copy the code

JSX binding properties

You can specify attribute values as string literals by using quotes:

const element = <div className="active"></div>
Copy the code

We can also use curly braces to insert a JavaScript expression inside the attribute value:

const element = <img src={user.avatarUrl}></img>
Copy the code

When embedding JavaScript expressions in attributes, do not enclose quotation marks around braces. You should only use either quotation marks (for string values) or braces (for expressions). You cannot use both symbols for the same attribute.

Event listeners

Different from native binding

What if the native DOM native has a listening event?

  • Method 1: ObtainDOMNative, add listening events;
  • Method two: inHTMLNative, direct bindingonclick;

Let’s practice method two here:

  • btnClick()And the reason for that isonclickThe binding is followed by the following JavaScriptCode;
<button onclick="btnClick()">Point me</button>
<script>
  function btnClick() {
    console.log('Button clicked.')}</script>
Copy the code

How does React work?

Let’s implement event listening in React. There are two main differences

  • ReactEvents are named in small hump (camelCase) instead of pure lowercase;
  • We need to pass in an event handler with {}, which will be executed when the event occurs;
class App extends React.Component {
  render() {
    return (
      <div>
        <button onClick={this.btnClick}>Point me</button>
      </div>)}btnClick() {
    console.log('React button clicked ')}}Copy the code

The this binding for the event

You have to be careful with this in the JSX callback. In JavaScript, class methods do not bind this by default. If you forget to bind this.handleClick and pass it in onClick, this will be undefined when you call this function.

class LoggingButton extends React.Component {
  handleClick() {
    console.log('this is:'.this)}render() {
    // This syntax ensures that 'this' in' handleClick 'is bound.
    return <button onClick={()= > this.handleClick()}>Click me</button>}}Copy the code

If you want to see how bind and arrow use this differently, you can look at the differences between bind and arrow

Event Parameter passing

When executing an event function, it is possible that we need to get some parameter information: for example, the event object, other parameters

Case 1: Get the Event object

  • A lot of times we need to geteventObject to do something (such as block the default behavior)
  • If we don’t need itthis, then you can get it by passing in the function directlyeventObject;
class App extends React.Component {
  btnClick(e) {
    e.preventDefault()
    console.log(e)
  }
  render() {
    return (
      <div>
        <a href="https://xhs-rookies.com/" onClick={this.btnClick}>Point me</a>
      </div>)}}Copy the code

Case two: Get more parameters

  • When we have more arguments, our best bet is to pass in an arrow function, an active event function, and pass in other arguments that are relevant;
class App extends React.Component {
  render() {
    let data = {
      names: ['clothes'.'shoes'.'pants'],}return (
      <div>
        <a href="https://xhs-rookies.com/" onClick={this.aClick}>Point me</a>

        {data.names.map((item, index) => {
          return (
            <a href="#" onClick={(e)= >This. AClick (e, item, index)}> here is {item}</a>)})}</div>)}aClick(e, item, index) {
    e.preventDefault()
    console.log(item, index)
    console.log(e)
  }
}
Copy the code

Conditions apply colours to a drawing

In some cases, the content of the interface will display different content depending on the situation, or decide whether to render a part of the content:

In React, all the conditional judgments are the same as normal JavaScript code;

What are the common methods of conditional rendering?

Conditional statement

One way to do this is by conditional judgment when there is a lot of logic:

class App extends React.Component {
  render() {
    let data = {
      isLogin: true,}let titleJsx = null
    if (data.isLogin) {
      titleJsx = <h2>Welcome back ~</h2>
    } else {
      titleJsx = <h2>Please log in ~ first</h2>
    }

    return <div>{titleJsx}</div>}}Copy the code

Of course, we can also wrap it in a separate function:

class App extends React.Component {
  this.data = {
    isLogin: true
  }

  render() {
    return (
      <div>
        {this.getTitleJsx()}
      </div>)}getTitleJsx() {
    let titleJsx = null;
    if (this.data.isLogin) {
      titleJsx = <h2>Welcome back ~</h2>
    } else {
      titleJsx = <h2>Please log in ~ first</h2>
    }
    returntitleJsx; }}Copy the code

Ternary operator

Another way to implement conditional rendering is the ternary operator condition? true : false;

Ternary operators are good for code without much logic: they simply return different results depending on different conditions

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      isLogin: true,}}render() {
    return (
      <div>
        <h2>{this.state.isLogin ? 'Welcome back ~' :' Please log in ~'}</h2>
        <button onClick={(e)= >this.loginBtnClick()}> {this.state.isLogin ? 'Exit' : 'login '}</button>
      </div>)}loginBtnClick() {
    this.setState({
      isLogin:!this.state.isLogin,
    })
  }
}
Copy the code

The and operator &&

In some cases, we have a scenario like this:

  • If true, render a component;
  • If the condition is not true, nothing is rendered;

What if we use a ternary operator?

{
  this.state.isLogin ? <h2>{this.state.username}</h2> : null
}
Copy the code

In fact, we can simplify the operation by using logic && :

{
  this.state.isLogin && <h2>{this.state.username}</h2>
}
Copy the code

The list of rendering

The list of rendering

During development we will request a large amount of data from the server, and the data will be stored as an array.

We need to organize the data in JavaScript code into JSX.

Let’s rehearse a case:

class App extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      skills: ['HTML'.'CSS'.'JavaScript'.'React'.'Node'].}}render() {
    return (
      <div>
        <h2>The front-end skills</h2>
        <ul>
          {this.state.skills.map((item) => {
            return <li>{item}</li>
          })}
        </ul>
      </div>
    )
  }
}

ReactDOM.render(<App />.document.getElementById('app'))
Copy the code

Array processing

Most of the time we need to do something with an array before we can show it:

  • For example, filtering out some content:filterfunction
  • For example, to intercept a portion of an array:slicefunction

For example, I currently have an array containing a series of numbers: [10, 30, 120, 453, 55, 78, 111, 222]

Example requirements: Get all numbers greater than or equal to 50 from a given array and display the first three numbers

class App extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      numbers: [10.30.120.453.55.78.111.222].}}render() {
    return (
      <div>
        <h2>Digital list</h2>
        <ul>
          {this.state.numbers
            .filter((item) => item >= 50)
            .slice(0, 3)
            .map((item) => {
              return <li>{item}</li>
            })}
        </ul>
      </div>
    )
  }
}

ReactDOM.render(<App />.document.getElementById('app'))
Copy the code

A list of key

We’ll notice in the previous code that whenever we present a list, we get a warning:

List display warnings

This warning tells us that we need to add a key to the JSX shown in the list.

As for why you need a key, there are rules for rendering the React component. When a long list or a DOM node’s child element sends a change, such as adding a new element at the end of the child element list, you just need to place the new content at the end.

But if you need to add a new element to the head of the list, it can be very expensive. To solve this problem, React introduced a method that improved tree conversion efficiency after key optimization.

For details about key, please see:

List & Key — React (reactjs.org)

Understand why key is necessary

JSX principle analysis

JSX transformation nature

In fact, JSX is just react. createElement(Component, props,… The syntactic sugar of the children function. All JSX will eventually be converted to function calls to React. CreateElement. If you want to learn more about how JSX works, see JSX in Depth

Case practice

The list shows

In real development, our data is usually fetched from the server, and it is more common to fetch a list of data and store it in an array for display

  • For example, now we have a to-do list. How do we present it with React?

Again, we do this with a component:

class App extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      things: ['Write an article'.'meeting'.'class'.'read'].}}render() {
    return (
      <div>
        <h2>To-do list</h2>
        <ul>
          {this.state.things.map((item, index) => {
            return <li>{index + 1 + '.' + item}</li>
          })}
        </ul>
      </div>)}}Copy the code

The case of “Like” function

There is no interaction in the todo list case, so let’s implement a “like” case:

class App extends React.PureComponent {
  constructor() {
    super(a)this.state = {
      isLike: false.likeNum: 233,}}likeOrUnlike() {
    if (this.state.isLike) {
      this.setState({
        isLike: false.likeNum: this.state.likeNum - 1})},else {
      this.setState({
        isLike: true.likeNum: this.state.likeNum + 1,}}}render() {
    console.log('render')
    return (
      <div>
        <p>{this.state.likenum}</p>
        <button onClick={(e)= >this.likeOrUnlike()}> {this.state.isLike ? 'Unlike' : 'like '}</button>
      </div>)}}Copy the code