Getting started with React - JSX and element rendering

What is JSX

const element = <h1>Hello, world!</h1>;

        The above tag syntax is neither string nor HTML, it is called JSX, which is a syntax extension of JavaScript. JSX is somewhat like a templating language, but it has the full power of JavaScript. JSX can generate React "elements".

        JSX tags can contain many child elements:

const element = (
  <div>
    <h1>Hello!</h1>
    <h2>Good to see you here.</h2>
  </div>
);

Embed expressions in JSX

const name = 'Josh Perez';
const element = <h1>Hello, {name}</h1>;

        In JSX syntax, any valid Javascript expression can be placed inside curly braces:

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

const user = {
  firstName: 'Harper',
  lastName: 'Perez'
};

const element = (
  <h1>
    Hello, {formatName(user)}!  </h1>
);

JSX is also an expression

        JSX is also an expression and can be called in a JavaScript method:

function getGreeting(user) {
  if (user) {
    return <h1>Hello, {formatName(user)}!</h1>;  
  }
  return <h1>Hello, Stranger.</h1>;
}

Specify attributes in JSX

        Property values ​​can be specified as string literals by using quotes:

const element = <a href="https://www.reactjs.org"> link </a>;

        Curly braces can also be used to insert a JavaScript expression within an attribute value:

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

        When embedding a JavaScript expression in an attribute, you cannot put quotes around the curly braces. Only one of quotes (for string values) or braces (for expressions) should be used, not both for the same property.

        Because JSX is syntactically closer to JavaScript than HTML, React DOM uses camelCase (small camel case naming) to define the names of attributes, instead of using the naming convention of HTML attribute names.

        For example, class in JSX becomes  className and tabindex becomes  tabIndex .

element rendering

        Call the createRoot method to create the root node, and then call the render method to render elements under the root node:

import { createRoot } from "react-dom/client";

const element = <h1>Hello, world</h1>;
const container = document.getElementById("root");
const root = createRoot(container);
root.render(element);

        Element update, modify appeal code, add timer function:

import { createRoot } from "react-dom/client";

const container = document.getElementById("root");
const root = createRoot(container);

function tick() {
  const element = (
    <div>
      <h1>Hello, world!</h1>
      <h2>It is {new Date().toLocaleTimeString()}.</h2>
    </div>
  );
  root.render(element);
}
setInterval(tick, 1000);

        Running the code reveals that only the time part changes:

         React only updates what it needs to update.

Guess you like

Origin blog.csdn.net/evanyanglibo/article/details/124200358