React Series 2: core JSX syntax

Time:2021-9-23

Come and join us!

“Rookies of Xiaohe mountain”, provide technology related information and a series of basic articles for front-end developers. For a better user experience, please move to our official website Xiaoheshan rookies( https://xhs-rookies.com/ )Study and get the latest articles in time.

“Code tailor”, if you are interested in our article or want to make some suggestions, please pay attention to wechat“Rookies of Xiaohe mountain”Public account, contact us, you can also watch our articles on wechat. Every suggestion or approval is a great encouragement to us!

preface

In this section, we will teach you an interesting tag syntax, which is neither string nor stringHTML, he was calledJSX, it’s aJavaScriptWe propose to extend the syntax inReactUsed in conjunction withJSXJSXIt can be well describedUIIt should present its essential form of interaction.

This article will introduce you to the following:

  • knowJSXGrammar of
  • stayJSXEmbedded expression in
  • event listeners
  • conditional rendering
  • List rendering
  • JSXPrinciple analysis
  • Case exercise

Understand the syntax of JSX

What is JSX?

Let’s start with a code:

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

This paragraphelementWhat is the tag syntax for assignment to the right of variable declaration?

This interesting tag syntax is neither string nor stringHTML

It is calledJSX, it’s a JavaScriptSyntax extension for. We suggestReactUsed in conjunction withJSXJSXIt can be well described that the UI should present the essential form of interaction it should have.JSXIt may be reminiscent of template language, but it hasJavaScriptAll functions of.

be careful:aboutJSXAlthough it is a kind ofJavaScriptSyntax extension, but you can find that it can’t be used directly inHTMLIn, you need to usebabelAfter the conversion, it will automatically help me parse into the desired style.

Why use JSX?

ReactThink rendering logic is essentially different from othersUILogical internal coupling, for example, inUIYou need to bind and handle events, and notify when the state changes at some timeUIAnd the need toUIDisplay the prepared data in.

ReactInstead of artificially separating tags and logic into different files, they are stored together in a loosely coupled unit called “component” to realize the separation of concerns.

ReactNot mandatoryJSXBut most people find that inJavaScriptIn the codeJSXandUIWhen placed together, it will play a visual auxiliary role. It can also makeReactDisplay more useful error and warning messages.

Writing specification of JSX:

  • JSXTop layer ofThere can only be one root elementSo we often wrap one in the outer layerdivPrimary;
  • In order to facilitate reading, we usuallyjsxThe outer layer of the is wrapped with a parenthesis (), which is easy to read, andjsxLine feed writing can be performed;
  • JSXLabels in can be single labels or double labels;

be careful:If it is a single label, it must be/>ending;

Embedding expressions in JSX

If wejsxThe content in is dynamic. We can get it through expression:

Writing rules: {expression}, which can be variables, strings, arrays, function calls, etcjsexpression;

Comments in JSX

This is embedded intoJavaScriptA syntax in, so when writing comments, you need to passJSXTo write in the following syntax:

<div>
  {/ * I'm a comment * /}
  <h2>Hello World</h2>
</div>

JSX embedded variables

Case 1:When the variable isNumberStringArrayType can be displayed directly

Case 2:When the variable isnullundefinedBooleanType, the content is empty;

  • If you want to displaynullundefinedBoolean, you need to convert it to a string; There are many ways to convert, such astoStringMethods,, and empty string splicing,String(variable) and other methods;

Case 3:Object type cannot be a child element(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'm a comment * /}
          <h2>Hello React</h2>
        </div>

        <div>
          {/ * 1. You can directly display * /}
          <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'))

Why should null, undefined and Boolean be displayed as empty content in JSX?The reason is that a lot of judgment will be made in development;

  • When the judgment result is false, no content is displayed;
  • When the judgment result is true, a content is displayed;

JSX embedded expression

In JSX syntax, you can put any valid JavaScript expression within 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 into the<h1>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'))

JSX binding properties

You can specify the attribute value as a string literal by using quotation marks:

const element = <div className="active"></div>

You can also use curly braces to insert a in the attribute valueJavaScriptexpression:

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

Embedding in attributesJavaScriptWhen using expressions, do not put quotation marks around braces. You should only use one of quotation marks (for string values) or curly braces (for expressions). You can’t use both symbols for the same attribute.

event listeners

And native binding

If nativeDOMThe native has a listening event. How can we operate?

  • Method 1: obtainDOMNative, add listening events;
  • Mode 2: inHTMLIn native, bind directlyonclick

Let’s practice mode 2 here:

  • btnClick()The reason for this isonclickBinding is followed by following JavaScriptcode;
< button onclick = "btnclick()" > Click me < / button >
<script>
  function btnClick() {
    Console.log ('button clicked ')
  }
</script>

stayReactHow to operate in?

Let’s do itReactThere are two main differences in event monitoring in

  • ReactThe event is named in the form of small hump(camelCase), not pure lowercase;
  • We need to pass in an event handling function through {}, which will be executed when the event occurs;
class App extends React.Component {
  render() {
    return (
      <div>
        < button onclick = {this. Btnclick} > Click me < / button >
      </div>
    )
  }

  btnClick() {
    Console.log ('click the react button ')
  }
}

This binding for event

You must be carefulJSXIn callback functionthis, inJavaScriptIn,classThe method of does not bind by defaultthis。 If you forget to bindthis.handleClickAnd passed it inonClick, when you call this functionthisThe value of isundefined

class LoggingButton extends React.Component {
  handleClick() {
    console.log('this is:', this)
  }

  render() {
    //This syntax ensures that 'this' within' handleclick 'is bound.
    return <button onClick={() => this.handleClick()}>Click me</button>
  }
}

If you want to knowbindAnd arrow function pairsthisYou can choose to view the differences between bind and arrow functions

Event parameter passing

When executing the event function, we may need to obtain some parameter information: for exampleeventObject, other parameters

Case 1: acquisitioneventobject

  • Many times we need to geteventObject to do something (such as blocking default behavior)
  • If we can’t use itthis, then you can get it by directly passing in the functioneventObject;
class App extends React.Component {
  btnClick(e) {
    e.preventDefault()
    console.log(e)
  }
  render() {
    return (
      <div>
        <a href="https://xhs-rookies.com/" onClick={this.btnClick}>
          Click on me
        </a>
      </div>
    )
  }
}

Case 2: get more parameters

  • When there are more parameters, the best way is to pass in an arrow function, an active event function, and other related parameters;
class App extends React.Component {
  render() {
    let data = {
      Names: ['clothes',' shoes', 'pants'],
    }
    return (
      <div>
        <a href="https://xhs-rookies.com/" onClick={this.aClick}>
          Click on me
        </a>

        {data.names.map((item, index) => {
          return (
            <a href="#" onClick={(e) => this.aClick(e, item, index)}>
              This is {item}
            </a>
          )
        })}
      </div>
    )
  }

  aClick(e, item, index) {
    e.preventDefault()
    console.log(item, index)
    console.log(e)
  }
}

conditional rendering

In some cases, the contents of the interface will display different contents according to different situations, or decide whether to render some contents:

stayReactIn, all conditional judgments are the same as ordinary onesJavaScriptConsistent code;

What are the common ways of conditional rendering?

Conditional judgment statement

One way is to judge by conditions when there are many logics:

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>
  }
}

Of course, we can also encapsulate it into an independent 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>
    }
    return titleJsx;
  }
}

Ternary operator

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

Ternary operators are suitable for code that does not have much logic: they just return different results directly according to 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,
    })
  }
}

And operator&&

In some cases, we will encounter such a scenario:

  • If the condition holds, render a component;
  • If the conditions are not established, nothing will be rendered;

If we use ternary operators, how do we do it?

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

In fact, we can passLogic and&&To simplify operations:

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

List rendering

List rendering

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

We need to passJavaScriptOrganize data by code and convert it intoJSX

Let’s practice a case:

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

    this.state = {
      skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Node'],
    }
  }

  render() {
    return (
      <div>
        <h2>Front end skills</h2>
        <ul>
          {this.state.skills.map((item) => {
            return <li>{item}</li>
          })}
        </ul>
      </div>
    )
  }
}

ReactDOM.render(<App />, document.getElementById('app'))

Array processing

Many times, we need to process the data in an array before displaying it:

  • For example, filter out some contents:filterfunction
  • For example, intercept part of the contents of the array:slicefunction

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

Case requirements: obtain all numbers greater than or equal to 50 from the 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'))

Key of the list

We will find that in the previous code, a warning will be given whenever the list is displayed:

React Series 2: core JSX syntaxList display warnings

This warning tells us what we need to show in the listjsxAdd akey

As for whykey, this involvesreactThe rules of component rendering, especially when the list is very long, orDOMWhen sending changes to the child elements of a node, for example, when adding new elements at the end of the child element list, you just need to place the new contents at the end, which is no problem.

However, if you need to add elements at the head of the list, the overhead will be very large. To solve this similar problem,ReactIntroduced. After using key for optimization, the conversion efficiency of the tree will be improved.

For details about key, see:

List & key – react (reactjs. ORG)

Understand why key is necessary

JSX principle analysis

JSX transformation essence

actually,jsxJustReact.createElement(component, props, ...children)Syntax of the function. All JSX will eventually be converted toReact.createElementFunction call for. If you want to know more aboutJSXPlease refer to JSX for the implementation principle of

Case exercise

List display

In real development, our data is usually obtained from the server. It is more common to obtain a list data and save it to an array for display

  • For example, there is a to-do list. How can we show it through react?

We still complete it through a component:

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

    this.state = {
      Things: ['writing an article', 'meeting', 'class',' reading '],
    }
  }

  render() {
    return (
      <div>
        <h2>To do list</h2>
        <ul>
          {this.state.things.map((item, index) => {
            return <li>{index + 1 + '.' + item}</li>
          })}
        </ul>
      </div>
    )
  }
}

Like function case

There is no interaction in the case of the to-do list. Let’s implement another case of the like function:

class App extends React.PureComponent {
  constructor() {
    super()
    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>Number of likes: {this. State. Likenum}</p>
        <button onClick={(e) => this.likeOrUnlike()}>
          {this. State. Islike? 'Cancel like': 'like'}
        </button>
      </div>
    )
  }
}

Recommended Today

Seven Python code review tools recommended

althoughPythonLanguage is one of the most flexible development languages at present, but developers often abuse its flexibility and even violate relevant standards. So PythoncodeThe following common quality problems often occur: Some unused modules have been imported Function is missing arguments in various calls The appropriate format indentation is missing Missing appropriate spaces before and after […]