React from entry to entry series 1-quick start

This is a series of React blogs organized by myself. It mainly refers to the content of the latest version of the official website of React that will be opened in March 2023. You are welcome to read the content of this series and hope to receive it.

After reading this article, you will gain:

  • How to create and nest react components
  • How to add markup and styles
  • How to display data
  • How to render conditionals and lists
  • How to respond to events and update the screen
  • How to share data between different components

1 How to create and nest react components

React applications are made up of components, which are parts of the user interface (UI) that have their own logic and appearance. The range of components is very large, it can be a complete page or a small button component. After react16, it is recommended that you use functional components combined with hooks to complete react application development*.

Note: If you don't know what functional components and hooks are, ignore these two concepts first, and we will introduce them later.

As a simple example, the following lines of code define the simplest react component:

function MyButton() {
    
    
    return (
        <button>我是一个按钮</button>
    )
}

MyButtonThen, you can use this component in other react components :

export default function MyApp() {
    
    
  return (
    <div>
      <h1>欢迎学习React</h1>
      <MyButton />
    </div>
  );
}

As shown in the chestnut above, MyAppit is a parent component that calls MyButtonthe component, so MyButtonit is also called a child component. Run the code above and you'll see:
insert image description here

Special note: It should be noted that the component names defined in React start with uppercase and follow the big camel case naming rules.

2 Write markup using JSX

The markup syntax that appeared in the previous sample code is called JSX (Javascript XML, an extension language of javascript), and its main feature is to write markup language in js code . Writing React components using JSX is optional, but most React projects will use JSX because it's really sweet and convenient (if you've used the optional API).

JSX is stricter than HTML. For example, you need to use <br />instead <br>, your component cannot return multiple JSX tags - if the component consists of multiple side-by-side tags, it needs to be used <div> ... </div>or <> ... </>wrapped in the outermost layer, as shown in the following code:

function AboutPage() {
    
    
  return (
    <>
      <h1>About</h1>
      <p>Hello there.<br />How do you do?</p>
    </>
  );
}

3 Add styles to your components

In React components, you can use to classNameadd a name to the element - just like setting the element in vuethe , but with a different name:templateclass

function AboutPage() {
    
    
  return (
    <>
      <h1 className="title">About</h1>
      <p>Hello there.<br />How do you do?</p>
    </>
  );
}

If you want to add styles to this component, you can create a AboutPage.cssfile and write the styles in it:

.title {
    
    
    font-size: 24px;
    color: green;
}

Then, AboutPage.jsreference the css style in:

import "./AboutPage.css";

function AboutPage() {
    
    
    ...
}

In addition to this way of writing, you can also define a AboutPage.module.cssfile with the same content AboutPage.cssas:

.title {
    
    
    font-size: 24px;
    color: green;
}

Then AboutPage.jsuse it like this:

import styles from "./AboutPage.module.css";
function AboutPage() {
    
    
  return (
    <>
      <h1 className={
    
    styles.title}>About</h1>
      <p>Hello there.<br />How do you do?</p>
    </>
  );
}

The advantage of this is: due to the use module css, the style pollution problem caused by the duplicate css name is avoided, and I prefer to use this way of writing.

4 Display data

JSX allows you to write markup language in Javascript code, and also supports the use of curly braces {}to escape data into Javascript, so you can embed some variables in JSX:

return (
  <h1>
    {
    
    user.name}
  </h1>
);

Using curly braces, you can also set attributes in the markup language as variables, for example: className="avatar"put the "avatar" string as a CSS class name, but src={user.imageUrl}put user.imageUrlthe variable value as imgthe tag's src attribute:

return (
  <img
    className="avatar"
    src={
    
    user.imageUrl}
  />
);

Going a step further, you can also treat objecttypes of data as variables:

return (
    <>
      <h1>{
    
    user.name}</h1>
      <img
        className="avatar"
        src={
    
    user.imageUrl}
        alt={
    
    'Photo of ' + user.name}
        style={
    
    {
    
    
          width: user.imageSize,
          height: user.imageSize
        }}
      />
    </>
  );
}

Note: In this example, style={ {}}it is not a special syntax, the innermost one {}is just the curly braces around an object.

5 Conditional rendering

There is no special syntax for writing conditional judgments in React (like , vuecan be used in v-if) , if you need to write conditional rendering statements, you only need to use or other branch statements v-elselike in Javascript . if-elseAs in the following example:

let content;
if (isLoggedIn) {
    
    
  content = <AdminPanel />;
} else {
    
    
  content = <LoginForm />;
}
return (
  <div>
    {
    
    content}
  </div>
);

Of course, you can also use ternary expressions to make the code look more elegant:

<div>
  {
    
    isLoggedIn ? (
    <AdminPanel />
  ) : (
    <LoginForm />
  )}
</div>

If you don't need to use the else branch, you can also write it like this:

<div>
  {
    
    isLoggedIn && <AdminPanel />}
  {
    
    isLogined ? <AdminPanel /> : null}
</div>

The writing of these conditional branches is also valid for attributes in JSX.

6 Render List

Suppose you have a list of product data like this:

const products = [
  {
    
     title: 'Cabbage', id: 1 },
  {
    
     title: 'Garlic', id: 2 },
  {
    
     title: 'Apple', id: 3 },
];

In React components, you can map()convert this array into <li>an array using a function:

const listItems = products.map(product =>
  <li key={
    
    product.id}>
    {
    
    product.title}
  </li>
);

return (
  <ul>{
    
    listItems}</ul>
);

Note: Components mapgenerated using traversal have a property, **For each item in the list, a string or number should be passed to the key property to uniquely identify the item among its siblings. **Usually, the value of key should come from your data, such as database ID. If your component subsequently inserts, deletes, or reorders items, React can use the key to distinguish who is who, thereby optimizing rendering performance.<li>key

7 Responding to events

You can respond to events by declaring event handlers in your components:

function MyButton() {
    
    
  function handleClick() {
    
    
    alert('You clicked me!');
  }

  return (
    <button onClick={
    
    handleClick}>
      Click me
    </button>
  );
}

Note: There are no parentheses onClick={handleClick}after handleClick, you don't need to add parentheses here .

8 Update screen

Typically, you want your component to remember some data from the component and display it. For example, you want to count the number of times a button is clicked. To achieve this, you need to add a state(state) to the component, and you need to use the first hookfunction - useState:

import {
    
     useState } from 'react';

countThen you can declare a variable and the corresponding update function as follows setCount, these are useStateprovided, just write as follows:

function MyButton() {
    
    
  const [count, setCount] = useState(0);

Then, you get two things: the current state ( count) and the update function of the state setCount. You can set their names at will, but they are generally [something, setSomething]named according to the style of .

countThe default value that will be displayed when the MyButon component is rendered for the first time 0. If you want to update countthe value, just call setCount()the method to update its value:

function MyButton() {
    
    
  const [count, setCount] = useState(0);

  function handleClick() {
    
    
    setCount(count + 1);
  }

  return (
    <button onClick={
    
    handleClick}>
      Clicked {
    
    count} times
    </button>
  );

The above code has implemented a fully-fledged stateReact component. When you click the button, countthe value of will be +1. If you render the same component multiple times, each component will have its own independent state, as in the following code:

import {
    
     useState } from 'react';

export default function MyApp() {
    
    
  return (
    <div>
      <h1>Counters that update separately</h1>
      <MyButton />
      <MyButton />
    </div>
  );
}

function MyButton() {
    
    
  const [count, setCount] = useState(0);

  function handleClick() {
    
    
    setCount(count + 1);
  }

  return (
    <button onClick={
    
    handleClick}>
      Clicked {
    
    count} times
    </button>
  );
}

operation result:
insert image description here

9 Using Hooks

By convention, usethe function starting with is called Hooks, useStatewhich is a built-in hook function of React. You will learn more hook functions in the follow-up study, and you can also check it in the API reference . You can also write your own hooks by combining existing hooks.

Compared with other functions, hooksit is more restrictive: you can only call hooks on top of components (or other hooks), if you want to use them in conditions or loops useState, you need to extract a new component and put it useStatein the correct position, Otherwise React will give warnings or even errors.

10 Sharing data among components

In the previous chestnut, MyButtonthe components exclusively share the data count, so clicking one of MyButtonthe components will not affect the value of the other:
insert image description here
so the question is, if you want two components to share data, what should you do?
If you want two sibling MyButtoncomponents to share data, you need to move the state up into their common parent component MyApp:
insert image description here
now, when you click either button, MyAppthe component countwill be updated, and the value in both components countwill be updated at the same time. So, how to write the code? Look at the code below:

export default function MyApp() {
    
    
  const [count, setCount] = useState(0);

  function handleClick() {
    
    
    setCount(count + 1);
  }

  return (
    <div>
      <h1>Counters that update separately</h1>
      <MyButton count={
    
    count} onClick={
    
    handleClick} />
      <MyButton count={
    
    count} onClick={
    
    handleClick} />
    </div>
  );
}

Pay attention to the content of the change: 1. Move the sum countfrom setCountthe MyButtoncomponent to the middle MyApp; 2. MyButtonAdd countthe sum to the component onClick(the data passed or the response function is called props), countwhich is the value passed from the parent component to the child component count; onClickyes Event handler function, once MyButtonthe button in is clicked, the function will be executed once in the parent component handleClick.

And MyButtonthe component will look like this:

function MyButton({
     
      count, onClick }) {
    
    
  return (
    <button onClick={
    
    onClick}>
      Clicked {
    
    count} times
    </button>
  );
}

The result of running the above code is as follows:
insert image description here

The end of this article, ( ).

Guess you like

Origin blog.csdn.net/qq_26822029/article/details/129718884