首頁 > web前端 > js教程 > 主體

React 初學者指南:基礎知識入門

王林
發布: 2024-08-16 06:11:03
原創
734 人瀏覽過

A Beginner’s Guide to React: Getting Started with the Basics

React 已成為現代 Web 開發的基石,以其高效、靈活性和強大的生態系統而聞名。 React 由 Facebook 開發,讓開發人員可以建立可重複使用的 UI 元件,從而簡化了建立互動式使用者介面的過程。

無論您是想建立複雜的單頁應用程式還是只是想提高您的 Web 開發技能,掌握 React 都是一筆寶貴的財富。

在本指南中,我們將引導您完成 React 入門的基本概念和步驟,包括設定開發環境、了解 React 基礎知識以及建立您的第一個元件。

什麼是反應?

React 是一個用於建立使用者介面的 JavaScript 程式庫,特別是對於需要動態和互動式使用者體驗的單頁應用程式。從本質上講,React 允許開發人員建立封裝的元件來管理自己的狀態並組合它們以創建複雜的 UI。 React 的聲明性質使您可以更輕鬆地推理應用程序,而其基於元件的架構則提高了可重複使用性和可維護性。

React 的簡史與演變

React 於 2013 年由 Facebook 首次發布,並因其構建 UI 的創新方法而迅速受到關注。與直接操作 DOM 的傳統函式庫和框架不同,React 引入了虛擬 DOM 的概念。這種抽象允許 React 透過僅更新已更改的 UI 部分來優化渲染,從而實現更有效率的效能。

自誕生以來,React 已經發生了顯著的發展,引入了鉤子、上下文 API 和並發渲染等功能。該庫擁有一個充滿活力的生態系統,圍繞它構建了大量工具、庫和框架,進一步增強了其功能。

React 的主要特點

  1. 基於元件的架構:React 基於元件的方法允許開發人員將複雜的UI 分解為更小的、可重用的部分,每個部分都有自己的邏輯和渲染。

  2. 虛擬 DOM:虛擬 DOM 是真實 DOM 的記憶體表示。 React 使用這個虛擬 DOM 透過與先前的狀態進行比較並僅套用必要的變更來有效地更新 UI。

  3. 聲明性語法:React 的聲明性語法透過描述任何給定狀態下的 UI 應該是什麼樣子,而不是指定如何更改 UI,使設計 UI 變得更加容易。

  4. 單向資料流:React 強制執行單向資料流,這表示資料從父元件流向子元件,從而更容易追蹤和管理狀態變更。

設定開發環境

在深入研究 React 之前,您應該對 HTML、CSS 和 JavaScript 有基本的了解。熟悉這些技術將幫助您更有效地掌握 React 概念,因為 React 建立在這些基本的 Web 技術之上。

安裝 Node.js 和 npm

React 開發需要 Node.js 和 npm(Node Package Manager),它們用於管理專案依賴關係和執行開發工具。

如何安裝 Node.js 和 npm:

  1. 下載並安裝 Node.js:前往 Node.js 官方網站並下載適合您作業系統的最新 LTS(長期支援)版本。此安裝套件包含npm。

  2. 驗證安裝:安裝後,打開終端機(或命令提示字元)並執行以下命令來驗證 Node.js 和 npm 是否已正確安裝:

   node -v
   npm -v
登入後複製

您應該會看到 Node.js 和 npm 的版本號,確認安裝成功。

創建反應應用程式

開始使用 React 最簡單的方法是使用 create-react-app 工具,該工具使用合理的預設配置來設定新的 React 專案。

初始化新 React 專案的逐步指南:

  1. 全域安裝 create-react-app:開啟終端機並執行:
   npx create-react-app my-app
登入後複製

將 my-app 替換為您想要的項目名稱。此命令使用給定名稱建立一個新目錄,並在其中設定一個 React 專案。

  1. Navigate to Your Project Directory:
   cd my-app
登入後複製
  1. Start the Development Server:
   npm start
登入後複製

This command runs the development server and opens your new React application in your default web browser. You should see a default React welcome page, indicating that everything is set up correctly.

Understanding React Basics

Components are the building blocks of a React application. They encapsulate UI elements and logic, making it easier to manage and reuse code. Components can be classified into two types:

  1. Functional Components: These are JavaScript functions that return React elements. They are often used for simple, stateless components.

Example:

   function Welcome(props) {
     return <h1>Hello, {props.name}</h1>;
   }
登入後複製
  1. Class Components: These are ES6 classes that extend React.Component and include a render method. They are used for more complex components with local state and lifecycle methods.

Example:

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

JSX (JavaScript XML)

JSX is a syntax extension for JavaScript that allows you to write HTML-like code within JavaScript. It makes it easier to create React elements and components.

How JSX is Transformed into JavaScript:

JSX is not valid JavaScript by itself. During the build process, a tool like Babel transforms JSX into regular JavaScript. For example:

JSX:

const element = <h1>Hello, world!</h1>;
登入後複製

Transformed JavaScript:

const element = React.createElement('h1', null, 'Hello, world!');
登入後複製

Props (Properties)

Props are used to pass data from a parent component to a child component. They are read-only and help make components reusable.

Example of Passing Props to a Component:

function Greeting(props) {
  return <p>Welcome, {props.username}!</p>;
}

function App() {
  return <Greeting username="Alice" />;
}
登入後複製

In this example, the Greeting component receives a username prop from the App component and displays it.

State

State allows components to manage their own data and react to user interactions. In functional components, the useState hook is used to manage state.

Introduction to the useState Hook:

The useState hook is a function that returns an array with two elements: the current state value and a function to update it.

Example of State Management Using useState:

import React, { useState } from 'react';

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

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}
登入後複製

In this example, the Counter component maintains a count state. Clicking the button updates the state, and the UI reflects the new count value.

Building Your First React Component

Let’s create a simple functional component to display a greeting message.

Step-by-Step Example:

  1. Create a New File: In the src directory of your project, create a file named Greeting.js.

  2. Define the Component:

   import React from 'react';

   function Greeting() {
     return <h1>Hello, React!</h1>;
   }

   export default Greeting;
登入後複製
  1. Render the Component: Open src/App.js and render the Greeting component.
   import React from 'react';
   import Greeting from './Greeting';

   function App() {
     return (
       <div className="App">
         <Greeting />
       </div>
     );
   }

   export default App;
登入後複製

Adding Basic Styles

You can style your components using inline styles or external CSS files. Here’s how to add basic styles:

  1. Inline Styles:
   function StyledGreeting() {
     const style = {
       color: 'blue',
       textAlign: 'center'
     };

     return <h1 style={style}>Hello, styled React!</h1>;
   }
登入後複製
  1. External CSS: Create a CSS file (Greeting.css) in the src directory.
   .greeting {
     color: green;
     text-align: center;
   }
登入後複製

Import the CSS file in Greeting.js and apply the class:

   import React from 'react';
   import './Greeting.css';

   function Greeting() {
     return <h1 className="greeting">Hello, styled React!</h1>;
   }

   export default Greeting;
登入後複製

Conclusion

React is a powerful library that enables developers to build dynamic and interactive user interfaces efficiently. In this guide, we covered the basics of React, including its core concepts, setting up the development environment, understanding components, JSX, props, and state, and building your first component. We also explored styling options to enhance your components.

以上是React 初學者指南:基礎知識入門的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!