首页 > web前端 > js教程 > 每个 React 概念都在几分钟内解释

每个 React 概念都在几分钟内解释

王林
发布: 2024-07-30 00:18:13
原创
271 人浏览过

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
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板