首頁 > web前端 > js教程 > 每個 React 概念都在幾分鐘內解釋

每個 React 概念都在幾分鐘內解釋

王林
發布: 2024-07-30 00:18:13
原創
284 人瀏覽過

React 是一個 JavaScript 函式庫,可讓您在幾分鐘內開發前端程式碼。它具有預先建立的方法和函數來執行某些任務。 React 作為一個函式庫包含複雜的術語,如協調、狀態、道具等。它們的實際意義是什麼?

透過這篇文章,你將更簡單地了解這個誇張的概念。

1. 組件

元件是一小段可重複使用的程式碼,它們傳回要在網頁上呈現的 React 元素。它是一組程式碼,組成了網頁的單一部分,如按鈕、導覽列、卡片等。它就像 JavaScript 函數,但傳回渲染的元素。它接受名為 "Props" 的參數。組件以大寫字母命名。

功能組件範例

function Heading(props) {
  return <h1>Join us, {props.name}!</h1>;
}
登入後複製

注意:

  • 建議使用函數式元件,而不是基於類別。
  • 函數式組件通常稱為無狀態組件。

2. JSX

JSX 是 JavaScript XML,它允許我們在 React 中編寫 HTML。它引入了類似 XML 的標籤和屬性來建立 React 元素。它允許您在 .jsx 檔案中編寫類似 HTML 的程式碼,從而輕鬆建立 React 元件。 JSX 沒有使用複雜的 JavaScript,而是讓程式碼變得可讀且乾淨。 React DOM 使用駝峰命名法進行屬性命名,例如 htmlFor、onClick。

JSX 範例

<h1 className="head">This is H1!</h1>
登入後複製

3. 碎片

React 中的片段可讓您從元件傳回多個元素。它會對元素清單進行分組,而無需建立額外的 DOM 節點。它會清除 DOM 中所有多餘的 div。這會快速渲染 UI。

片段範例

const App = () => {
  return  (
    <>
      <h1>Eat</h1>
      <button>Learn more</button>
      <p>Code is Fun</p>
      <button>Repeat</button>
    </>
  );
}
登入後複製

注意:

  • 片段使程式碼更清晰、可讀。
  • 記憶體效率更高。
  • 它不能有 CSS 樣式和鍵。

4. 道具

「Props」是 React 中的一個特殊關鍵字,代表屬性。它用於在組件之間傳輸資料。資料傳輸的遵循是單向的,即從父組件到子組件。

道具範例

function Head(props) {
  return <p>{props.children}</p>;
}
登入後複製

注意:Props 是唯讀的,這確保子元件不會操作來自父元件的值。

5. 狀態

當使用者互動時,元件需要追蹤某些值。假設當使用者點擊按鈕時,亮/​​暗模式主題切換按鈕會變更其值(從亮到暗,反之亦然)。組件需要記住主題的當前值。在 React 中,這種特定於元件的記憶體稱為狀態。

狀態是使用 useState() 鉤子定義的;稍後會詳細介紹。

定義狀態的範例

const [index, setIndex] = useState(0)
登入後複製

注意:在頂級組件中定義狀態始終是一個很好的做法,以便與其他子組件輕鬆共享它並確保單一事實來源。

6. 生命週期方法

生命週期方法是可以在 React 類別中使用的特殊函數,用於在元件存在的各個階段執行操作。這些階段是:

  • 安裝:當元件首次建立並插入 DOM 時。
  • 更新:當元件的 props 或 state 發生變化時,導致元件重新渲染。
  • 卸載:當元件從 DOM 移除。

7. 純潔

函數式程式設計中的純度是指給定的相同輸入返回相同的輸出。輸入是決定輸出的唯一因素,則該函數稱為純函數。

在 React 中,當一個元件為相同的輸入(即 props)傳回相同的輸出時,該元件稱為純元件

8. 嚴格模式

嚴格模式是 React 中的開發功能,可啟用額外的安全功能來提高程式碼品質。它顯示有關程式碼中潛在錯誤和錯誤的警告。它將警告記錄到瀏覽器的控制台中。

嚴格模式範例

import { StrictMode } from 'react';

function App() {
  return (
    <>
     <StrictMode>
        <Header />
        <Sidebar />
        <Content />
        <Footer />
     </StrictMode>
    </>
  )
}
登入後複製


Every React Concept Explained in inutes

React 中的嚴格模式顯示瀏覽器控制台

9. 鉤子

React 中的 Hooks 允許使用狀態和其他 React 功能,而無需編寫類別元件。 Hooks 是提供對 React 狀態管理、副作用和其他功能的存取的函數。

一些常用的hook:useState、useMemo、useRef等

Hook 範例

import React, { useState } from "react"; // Importing useState hook;

function FavoriteColor() {
  const [color, setColor] = useState("red"); // Initializing the state and setter function;

  return (
    <>
      <h1>My favorite color is {color}!</h1>
      <button
        type="button"
        onClick={() => setColor("blue")} // Updating the state;
        >Blue</button>
      <button
        type="button"
        onClick={() => setColor("red")} // Updating the state;
      >Red</button>
      <button
        type="button"
        onClick={() => setColor("yellow")} // Updating the state;
      >Yellow</button>
      </>
  );
}
登入後複製

注意:

  • Hooks can only be called inside React function components.
  • Hooks can only be called at the top level of a component.
  • Hooks cannot be conditional.

10. Context API

The Context API is used to share data like state, functions across the component tree without passing props down manually at every level. It avoids prop drilling by simplifying state management and sharing data across the component. With Context API the data is shared directly with the child component who will consume it.

The useContext() method is used to create a context. This function returns a context object with two components – a Provider and a Consumer.

The Provider is used to wrap the part of your component tree where you want the context to be available. It accepts a compulsory value prop that holds the data you want to share across other components.

The useContext hook is used to access the data.

Example of Context API

Create a context using createContext() method. Wrap child components in the Context Provider and supply the state value.

import { useState, createContext} from "react";

const UserContext = createContext();

function ParentCounter() {
  const [count, setCount] = useState(10);

  return (
    <UserContext.Provider value={count}>
      <h1>{`Current Count: ${count}!`}</h1>
      <Button />
    </UserContext.Provider>
  );
}
登入後複製

Use useContext hook to access the value of age.

import { useContext } from "react";

function GrandChildConsumer() {
  const age = useContext(UserContext);

  return (
    <>
      <h1>This is GrandChildConsumer</h1>
      <h2>{`Current Count: ${count}`}</h2>
    </>
  );
}
登入後複製
Note: The `useContext` hook is often used instead of Consumer for better readability and simplicity.

11. Lists and Keys

A Key is a special kind of attribute for list items in React. It acts as a unique identifier for each items when it is updated, deleted, or added.

Assigning index of the item as the Key is discouraged because if the items are rearranged it will affect the expected behavior.

Imagine in shopping cart you have 10 items added and each item have a unique index as a Key. Now, you decide to remove the first and fifth item from the cart. When the items are removed the indexing will change; the second item will become first and sixth item will become fifth item.

Example of Lists and Keys

const fruits = ["apple", "banana", "orange"];

function FruitList() {
  return (
    <ul>
      {fruits.map((fruit, index) => (
        <li key={index}> {fruit} </li>
      ))}
    </ul>
  );
}


登入後複製
Note:
  • It is recommended to use string as a `Key` that uniquely identifies the item in the list.
  • Third-party libraries like UUID offer the functionality to create unique keys.

12. Form: Controlled & Uncontrolled Components

React forms allows to collect and manage user input better than traditional HTML form. These forms are built using components and store the user inputs into state. There are two types of components:

Controlled Components

In Controlled components, the form's state is managed by the component himself. This is the recommended approach for managing form data in React. When the user interacts with the form (e.g., typing in an input field), the component's state is updated to reflect the changes.

Example of Controlled Component

function ControlledInput() {
  const [name, setName] = useState('');

  const handleChange = (e) => {
    setName(e.target.value);
  }

  return (
    <div>
      <label htmlFor="name">Name: </label>
      <input type="text" id="name" value={name} onChange={handleChange} />
      <p>Your name is: {name}</p>
    </div>
  );
}
登入後複製

Uncontrolled Components

Uncontrolled components rely on the DOM to manage the form data. The component doesn't directly control the form's state, but it can access the values using DOM methods like ref.

Example of Uncontrolled Component

function UncontrolledInput() {
  const nameRef = useRef(null);

  const handleClick = () => {
    console.log(nameRef.current.value);
  }

  return (
    <div>
      <label htmlFor="name">Name: </label>
      <input type="text" id="name" ref={nameRef} />
      <button onClick={handleClick}>Get Name</button>
    </div>
  );
}
登入後複製

Note:

  • Controlled components provides form validation because the user's input is instantly reflected due to use of state.
  • Form validation is not possible in uncontrolled components because the user's input can only be accessed after the form is submitted.

13. React Router

  • Introduction to React Router for navigation
  • Basic setup and usage
  • Example: Creating routes and navigating between pages

React Router is a standard library for routing in React. It enables navigation among various components in the React app. It allows changing the browser URL and syncing the UI with the URL. React Router is important for creating single-page applications (SPA) with navigation features.

First, you need to install React Router from your terminal.

Installing React Router

# If you are using npm
npm install react-router-dom

# If you are using yarn
yarn add react-router-dom
登入後複製

Example of React Router

import { BrowserRouter, Routes, Route } from "react-router-dom";
import Home from "./pages/Home";
import About from "./pages/About";
import Contact from "./pages/Contact";
import NoPage from "./pages/NoPage";

export default function App() {
  return (
    <BrowserRouter>
      <Routes>
          <Route path="/" element={<Home />} />
          <Route path="about" element={<About />} />
          <Route path="contact" element={<Contact />} />
          <Route path="*" element={<NoPage />} />
      </Routes>
    </BrowserRouter>
  );
}
登入後複製

First wrap your content into the . Then we define and inside that introduces the for navigation. has path which specifies URL of the page and element attribute which specifies the component that needs to be rendered on the defined path.

Note:

  • 一個應用程式可以有多個.
  • 可以嵌套。
  • `react-router-dom`也有且導航元件。

結論

學習任何程式語言的最好方法就是練習更多的專案。建立小型專案並嘗試這些概念。

如果您覺得這篇文章有幫助,請不要忘記繼續向我表達愛意。下次記得按讚、分享、學習。

您也可以透過在此處以及 X、GitHub 和 LinkedIn 上關注我來與我保持聯繫。

以上是每個 React 概念都在幾分鐘內解釋的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板