React: The Past and Present

React official features

Declarative, componentized, learn once, write anywhereCopy the code

We won’t cover installing react here. Let’s look at the JSX syntax in React.

What is JSX syntax

One of the core mechanisms of React is the ability to create virtual DOM elements in memory. React leverages the virtual DOM to reduce manipulation of the real DOM to improve performance.

JSX is a combination of Javascript and XML. React invented JSX, which uses HTML syntax to create a virtual DOM. JSX treats < as HTML parsing and {as JavaScript parsing.Copy the code
Var child1 = react. createElement('li', null, 'First Text Content');
   var child2 = React.createElement('li', null, 'Second Text Content');
   var root = React.createElement('ul', { className: 'my-list'}, child1, child2); Equivalent to (JSX) var root =(<ul className="my-list">
     <li>First Text Content</li>
     <li>Second Text Content</li>
     </ul>
   );
Copy the code

The latter adds XML syntax directly to JS, effectively defining interfaces through code rather than templates. JSX is then converted to pure JS by a translator and executed by the browser.

Basic usage of JSX

  • expression

    Because JSX has javascript inside curly braces, you can only add expressions (including ternary operators), and if you fill in what’s included in quotes, it defaults to a string.

    ReactDOM.render(
    <div>
      <h1>{1+1}</h1>
      <h2>{i == 1 ? 'True! ' : 'False'}</h2>
    </div>,
    document.getElementById('example'));Copy the code
  • style

    React recommends using inline styles. We can use camelCase syntax to set inline styles.

    var myStyle = {
    fontSize: 100,
    color: '#FF0000'}; <h1 style = {myStyle}> </h1>, document.getelementByid ('example'));Copy the code
  • annotation

    Comments are special when written in JSX and need to be enclosed in braces.

    Reactdom.render (<div> <h1> </h1> {/* annotation... */} </div>, document.getElementById('example'));Copy the code
  • In array JSX, if you want to render a list of data, instead of using a for method like Vue, you loop through some array method (map). At the same time, JSX allows you to insert arrays into templates that automatically expand all the members.

    Var arr = [<h1> </h1>, <h2>,]; ReactDOM.render( <div> {arr} <ul> {arr.map(item => {return <li>{item}</li>;
        })}
        </ul>
      </div>,
      document.getElementById('example'));Copy the code

The benefits of JSX

  • JSX executes faster because it is optimized after being compiled into JavaScript code.
  • It is type-safe and errors can be found during compilation.
  • Using JSX to write templates is much easier and faster.

End four.

React JSX syntax Is one of the core JSX syntax of React. With this syntax, we can write better and faster code. If you have any more react fun things, feel free to leave them in the comments

React: The Past and Present

Author: She