react preliminary learning

What is React?

React is a declarative, efficient and flexible JavaScript library for building user interfaces

  the simplest example of React

ReactDom.render(
    <h1>Hello World</h1>,
    document.getElementById('root')
)

  ReactDom.render accepts two parameters, the first is the content to be inserted, and the second is inserted into DOM or index Location of HTML

A simple component compared with Html

  the following is a React component

class ShoppingList extends React.Componnet {
    render() {
        return (
            <div className="shopping-list">
                <h1>Shoping List for {this.props.name}</h1>
                <ul>
                    <li>Instagram</li>
                    <li>WhatApp</li>
                    <li>Oculus</li>
                </ul>
            </div>
        )
    }
}

// Example usage:  <ShoppingList name="Mark" />

  here, ShoppingList is a React component class or a React component type. The component accepts parameters, called property props, and returns a realistic view hierarchy through the render method.

  the render method returns the description of the content you want to render, and then React accepts the description and renders it to the screen. In particular, render returns a React element, which is a lightweight description of the rendered content. majority
React developers use JSX syntax, which is also the syntax written in the above case.

  the conversion rule of JSX syntax is: < div / > syntax is converted to react during construction createElement('div'). Therefore, the above example is equivalent to:

return React.createElement('div', {className: 'shopping-list'},
    React.createElement('h1', /* h1 children ... */),
    React.createElement('ul', /* ul children ... */)
);

  since JSX is so popular among React developers, what is JSX?

JSX syntax

  JSX is an extended syntax of Javascript, which can make your Javascript write HTML like normal description HTML.

  you can embed any Javascript expression in JSX with curly braces. For example: expression 1 + 2, variable user Firstname, and the function formatName(User) can be embedded

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

const user = {
    firstName: 'harper',
    lastName: 'Perez'
}

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

ReactDOM.render (
    element,
    document.getElementById('root')
)

  please note that for ease of reading, developers often wrap JSX in multiple lines, because this can be avoided Semicolon auto insert Traps, such as

{ 1
2 } 3
// is transformed to
{ 1
;2 ;} 3;

JSX is also an expression

  after compilation, the JSX expression becomes a regular javascript object

  because of this, we can use JSX in the if statement or this is a for loop statement to assign a value to a variable, accept it as a parameter, or as the return value of a function

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

Specifying attribute values with JSX

  you can embed a JavaScript expression with curly braces as the attribute value

// In quotation marks
const element = <div tableIndex="0"></div>;
// Use an expression, and the expression is wrapped in curly braces
const element = <img src={user.avatarUrl}></img>;

Specifying child elements with JSX

  if it is an empty label, it can be closed directly with / >

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

  if sub tags are included:

<div>
    <h1>Hello!</h1>
    <h2>Good to see you here.</h2>
</div>

JSX is closer to Javascript than HTML, so the React DOM specification uses the camel case attribute naming convention instead of the HTML attribute name. Of course, some attribute names of HTML are also reserved words and cannot be used, such as class;
Therefore, class becomes classname and tableIndex becomes tableIndex in JSX.

Render element to DOM

  normally, your index There will be such a div under the HTML file

<div id='root'></div>

  this root DOM node is hung at all React DOM locations. Under normal circumstances, for the construction of a React single page application, only a separate root DOM node is required. However, if React is to be integrated into the existing APP, multiple DOM nodes may be used.

  React uses the render method to render the React element to the DOM. Once the element is rendered to the page, you can't modify the attributes of the sub element or any element in the modifier, just like a frame in the movie. What about the UI effect at a specific point in time? Yes, re render

function tick() {
    cosnt element = {
        <div>
            <h1>Hello, world</h1>
            <h2>It is {new Date().toLocaleTimeString()}.</h2>
        </div>
    };
    ReactDom.render (
        element,
        document.getElementById('root')
    )
}

setInterval(tick, 1000);

In fact, most React applications call reactdom only once Render (), and the way to implement component update is to encapsulate the code in stateful components.

React updates only those parts that must be updated

  this is the strength of react. React DOM will compare the elements and their child elements with previous versions one by one, and only update the DOM that needs to be updated to achieve the state required by the dom.

  in the development process, we should pay more attention to the UI performance at each point in time, rather than focusing on constantly updating the UI status over time, which can reduce many strange bug s

Components and properties

  component components and property props, where property is the code abbreviation of the word property.

Two ways to define components

  there are two ways to define components

  1. Functional component definition
  2. Class component definition
      the simplest way to define a component is to write a Javascript function

function Welcome(props)  {
    return <h1>Hello, props.name</h1>
}

  this is a valid component. It starts with a props parameter and returns a React element. This is a functional component. On the surface, it is a Javascript function.

  the definition of class components depends on the class of ES6. The following definition method is equivalent to the above;

class Welcome extends React.Component {
    render() {
        return <h1>Hello, {this.props.name}</h1>;
    }
}

Render a component

// DOM tags as components
const element = <div />;
// React element as component
const element = <Welcome name="Sara" />;

  when React encounters an element representing a user-defined component, it treats the JSX attribute as a separate object, that is
The props object is passed to the corresponding component, such as

function Welcome(props) {
    return <h1>Hello, {props.mname] </h1>;
}
const element = <Wlecome name="Sara" />;
ReactDOM.render(
    element,
    document.getElementById('root')
)

[understanding]

  1. Call reactdom Render() method and passed in the < welcome name = "Sara" / > element
  2. Raect calls the Welcome component and passes {name: 'Sara'} as the props object
  3. The Welcome component returns < H1 > Hello, Sara</h1>
  4. React DOM quickly updates the DOM to display as < H1 > Hello, Sara</h1>

Component names always start with uppercase letters, such as < welcome / > in this example, rather than < welcome / >

Constituent components

  since a component is a single React element, it can work alone, so we can reference the same component multiple times in a React element, for example:

function Welcome(props) {
    return <h1>Hello, {props.name}</h1>
}
function App() {
    return (
        <Welcome name="Sara" />
        <Welcome name="Lucy" />
        <Welcome name="Edite" />
    )
}

ReactDOM.render(
    <App />,
    document.getElementBuId('root')
)

  generally, React apps have a separate top-level App component. If you integrate React into an existing application, you also need to gradually integrate it from the small components from the bottom to the top to the components at the top of the view.

The component must return a single root element, which is why we add a < div > to wrap all < welcome / > elements

Extract component

  for a React element, if it contains reusable or reusable content, don't be afraid to take out multiple smaller components.

  extracting components may seem like a tedious task, but in large apps, we can get a lot of reusable components back. A good rule of thumb is that if a part of your UI needs to be used multiple times (Button, Panel, Avatar), or it is complex enough (App, FeedStory, Comment), the best way is to make it a reusable component.

Props is read-only

  whatever you use Function or class To declare components,

  although React is flexible, it has a strict rule: * * all React components must be pure functions, and it is forbidden to modify their own props * *. The so-called pure function is: the parameters of the incoming function will not change during the execution of the function, such as the self increment operation a + +.

  if props is read-only, can't the parameters passed to child elements (child components) be modified? How do child elements interact with parent elements? React also provides us with the state attribute state for us to modify the value inside the subcomponent

Keywords: React

Added by tibberous on Fri, 14 Jan 2022 03:11:56 +0200