」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > React 函式庫簡介:)

React 函式庫簡介:)

發佈於2024-11-08
瀏覽:776

It is a popular open-source JavaScript library used for building user interfaces, particularly single-page applications (SPA).

Isomorphic

Technology is isomorphic when it can run in both server and client
Ex. React JS, Next JS

Know how

Browsers don’t support directly including or loading JavaScript files from within other JavaScript files. The loading of JavaScript files is managed by the HTML document through script tags.

But, once installed as a package, we need something to
put all the code together that can be included in the HTML so that the browser can get access to the code. For this, there are build tools such as browserify or webpack that can
put together your own modules as well as third-party libraries in a bundle that can be included in the HTML.

Important features of ReactJs

Component-Based Architecture
It helps to create components that manages it's own state

Supports server-side rendering as well as client-side rendering

Virtual DOM:
When the state of an object changes, React updates the virtual DOM first, and then it efficiently updates the real DOM only where changes have occurred. It uses diffing algorithm to detect changes periodically

Introduction to React Library :)

JSX Syntax:
React uses JSX (JavaScript XML), a syntax extension that allows you to write HTML directly within JavaScript.

MVC (Model View Controller)

It is a design pattern in which application is separated into three interconnected components

Model

Represent the business and data logic. This can include fetching data from a server, interacting with a database, or managing in-memory data(State management).

View

Represent rendering of UI and presenting data to the user


// UserView.js
import React from 'react';

// This is a simple React functional component that acts as the View
function UserView({ user }) {
  return (
    

User Information

Name: {user.name}

Email: {user.email}

); } export default UserView;

Controller

Manages the interaction between Model and View. It handles user input, manipulates data through the Model, and updates the View


// UserController.js
import React, { useState, useEffect } from 'react';
import UserView from './UserView';
import { fetchUserData, updateUserData } from './model';

function UserController() {
  const [user, setUser] = useState(null);

  useEffect(() => {
    // Fetch user data when the component mounts
    const userData = fetchUserData();
    setUser(userData);
  }, []);

  const handleUpdate = () => {
    // Update user data and refresh view
    const newData = { name: 'Jane Doe', email: '[email protected]' };
    updateUserData(newData);
    setUser(newData); // Update local state to reflect changes
  };

  if (!user) {
    return 
Loading...
; } return (
); } export default UserController;

Class Component


import React, { Component } from 'react';

// Define the class component
class MyComponent extends Component {
  // Initial state
  constructor(props) {
    super(props);
    this.state = {
      // Define your initial state here
      count: 0
    };

    // Bind event handlers if necessary
    this.handleClick = this.handleClick.bind(this);
  }

  // Lifecycle method: componentDidMount
  componentDidMount() {
    // Code to run after the component has been mounted
    console.log('Component did mount');
  }

  // Lifecycle method: componentDidUpdate
  componentDidUpdate(prevProps, prevState) {
    // Code to run after the component updates
    console.log('Component did update');
  }

  // Lifecycle method: componentWillUnmount
  componentWillUnmount() {
    // Code to run before the component unmounts
    console.log('Component will unmount');
  }

  // Event handler method
  handleClick() {
    this.setState(prevState => ({
      count: prevState.count   1
    }));
  }

  // Render method
  render() {
    return (
      

Hello, {this.props.name}!

Current count: {this.state.count}

); } } // Default props (optional) MyComponent.defaultProps = { name: 'World' }; export default MyComponent;

Props (short for properties)

They are read-only attributes passed from a parent component to a child component, enabling the sharing of data and configuration between components.

Props are like arguments you pass to a function. They let a parent component pass data to a child component and customize its appearance


//default value for props
function Avatar({ person, size = 100 }) {
  // ...
}
export default function Profile() {
  return (
    
  );
}


State

State is like a component’s memory. It lets a component keep track of some information and change it in response to interactions

state is fully private to the component declaring it

Event Propagation

events typically propagate through the DOM tree in two phases: the capture phase and the bubble phase.

Event Propagation Phases
Capture Phase: The event starts from the top of the DOM tree and travels down to the target element.
Bubble Phase: After reaching the target element, the event bubbles back up to the top of the DOM tree.


function handleDivClick() { console.log('Div clicked'); } function handleButtonClick1() { console.log('Button 1 clicked'); } function handleButtonClick2() { console.log('Button 2 clicked'); }

Click on Button 1:

The event is first captured and handled by handleButtonClick1().
After that, the event bubbles up to handleDivClick().

If you want to prevent the event from bubbling up to parent elements, you can use the event.stopPropagation() method within the button's onClick handler:


function handleButtonClick1(event) {
    event.stopPropagation();
    console.log('Button 1 clicked');
}


screen updates follow a lifecycle that involves three primary phases: Trigger, Render, and Commit.
Trigger
Description: This phase begins when an event or state change prompts an update in the React component
Render
Description: During this phase, React computes what the new UI should look like based on the changes. React performs a reconciliation process to determine the minimal set of changes required to update the DOM
Commit
Description: This is the final phase where React applies the changes to the actual DOM based on the diffing results

Batching:

Batching of state updates is a key optimization technique in React that helps improve performance by reducing the number of re-renders and DOM updates.
Batching refers to the process of grouping multiple state updates together into a single update.


function MyComponent() {
  const [count, setCount] = useState(0);
  const [text, setText] = useState('');

  const handleClick = () => {
    setCount(count   1);
    setText('Updated');
  };

  return (
    

Count: {count}

Text: {text}

); }

When handleClick is invoked by clicking the button, both setCount and setText are called.
React batches these state updates together, performs a single re-render, and applies both updates in one go.

Synthetic Event

It is an object that is a cross-browser wrapper around the native browser events. React implements its own event system to provide a consistent and performant way to handle events in a cross-browser manner.

React uses a single event listener for all events and delegates the event handling to a common parent element (the root of the DOM tree). This reduces the overhead of attaching and managing multiple event listeners.

Array

Map

In React, the map method is commonly used to render lists of data.


import React from 'react';

const UserList = () => {

const users = [
  { id: 1, name: 'John Doe', email: '[email protected]' },
  { id: 2, name: 'Jane Smith', email: '[email protected]' },
  { id: 3, name: 'Mike Johnson', email: '[email protected]' }
];

  return (
    

User List

    {users.map(user => (
  • {user.name}

    {user.email}

  • ))}
); }; export default UserList;

Filter

The filter method in JavaScript is used to create a new array with elements that pass the test implemented by the provided function


const chemists = people.filter(person =>
  person.profession === 'chemist'
);


React.Fragment

It allows you to group a list of children without adding extra nodes to the DOM



>


React.StrictMode

It provide warnings and hints to developers about best practices, deprecated features, and potential problems.
It encourages the use of modern React features like functional components, hooks;

Render Props

It is a powerful pattern to create components in which we pass a function/component as a prop to dynamically determine what to render.

This can be used when the parent component wants access the child component's functions and states

Child component


import React, { useState } from 'react';

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

  const increment = () => setCount(count   1);
  const decrement = () => setCount(count - 1);

  // Call the render prop function with the current count and control functions
  return render({ count, increment, decrement });
}

export default Counter;


Parent component


import React from 'react';
import Counter from './Counter';

function App() {
  return (
    

Counter Example

(

Current Count: {count}

)} />
); } export default App;

Difference between ES5 and ES6

Variables

ES5


var name = 'John';


ES6


let name = 'John';
const age = 30;


Function Declaration

ES5


//Arrow functions
var sum = function(a, b) {
  return a   b;
};



ES6


const sum = (a, b) => a   b;


Default Parameters


function greet(name) {
  var name = name || 'Guest';
  return 'Hello, '   name;
}


ES6


function greet(name = 'Guest') {
  return `Hello, ${name}`;
}


Destruction

Destructuring allows unpacking values from arrays or properties from objects into distinct variables.


var person = { name: 'John', age: 30 };
var name = person.name;
var age = person.age;


ES6


const person = { name: 'John', age: 30 };
const { name, age } = person;


Promises


function asyncOperation(callback) {
  setTimeout(function() {
    callback('result');
  }, 1000);
}


ES6


const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('result');
  }, 1000);
});

promise.then(result => console.log(result));


Import and Export

ES5


// CommonJS
// app.js
const math = require('./math.js');

//math.js
function add(a, b) {
  return a   b;
}

function subtract(a, b) {
  return a - b;
}

module.exports = {
  add,
  subtract
};


ES6


// Module
import { mod } from './dep.js';

// Exporting
export function mod() {
  return 'Hello';
}


Classes

ES5


function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.greet = function() {
  return 'Hello, '   this.name;
};


ES6


class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet() {
    return `Hello, ${this.name}`;
  }
}


Class component creation

ES5


var MyComponent = React.createClass({
    getInitialState: function() {
        return { count: 0 };
    },
    incrementCount: function() {
        this.setState({ count: this.state.count   1 });
    },
    render: function() {
        return (
            

Count: {this.state.count}

); } });

ES6


class MyComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = { count: 0 };
        this.incrementCount = this.incrementCount.bind(this);
    }

    incrementCount() {
        this.setState({ count: this.state.count   1 });
    }

    render() {
        return (
            

Count: {this.state.count}

); } }

Conditional/ternary Operation


{isLoggedIn ? ( ) : ( )}

Types of Components

Functional Components

These are the simplest type of React components. They are JavaScript functions that receive props as arguments and return JSX to be rendered. Functional components can be stateless or stateful with the help of Hooks.


// Functional Component
import React, { useState } from 'react';

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

  return (
    

You clicked {count} times

); }

Class Components

These components are more traditional and provide additional features compared to functional components, such as lifecycle methods. They are defined using ES6 classes and must extend React.Component

Important points:
It has all lifecycle methods (more overhead compared to functional components)
It is defined using ES6 classes
It is not concise and easy to read like functional components


import React, { Component } from 'react';

class Counter extends Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  increment = () => {
    this.setState({ count: this.state.count   1 });
  }

  componentDidMount() {
    console.log('Component mounted');
  }

  render() {
    return (
      

You clicked {this.state.count} times

); } }

Higher Order Components

HOCs are functions that take a component and return a new component with additional functionality or data.

Controlled Components

In controlled components, the form data is handled by the React component state. The state serves as the "single source of truth" for the input elements.


import React, { useState } from 'react';

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

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

  const handleSubmit = (event) => {
    event.preventDefault();
    alert(`A name was submitted: ${name}`);
  };

  return (
    
); } export default ControlledComponent;

Uncontrolled Components

In uncontrolled components, form data is handled by the DOM itself. Instead of using state to control form inputs, refs are used to access form values directly.
Refs are used to directly access and manipulate the DOM elements or to store mutable values that don’t trigger a re-render when changed.


import React, { useRef } from 'react';

function UncontrolledComponent() {
  const nameInput = useRef(null);

  const handleSubmit = (event) => {
    event.preventDefault();
    alert(`A name was submitted: ${nameInput.current.value}`);
  };

  return (
    
); } export default UncontrolledComponent;

Short-circuit evaluation

It is a technique used to conditionally render components or elements based on certain conditions.


function MyComponent({ isLoggedIn }) {
  return (
    

Welcome to the website!

{isLoggedIn &&

You are logged in!

}
); }

Difference between ES5 and ES6

es6 es5
require vs impor
export vs exports
var MyComponent = React.createClass({
render: function() {
return
class MyComponent extends React.Component

Difference between controlled and uncontrolled


import React, { useRef } from 'react';

function UncontrolledForm() {
  const inputRef = useRef(null);

  // Handle form submission
  const handleSubmit = (event) => {
    event.preventDefault();
    alert('Submitted value: '   inputRef.current.value); // Access value using ref
  };

  return (
    
); } export default UncontrolledForm;

State Management:

Controlled Components: State is managed by React.
Uncontrolled Components: State is managed by the DOM.
Form Element Values:

Controlled Components: Value is controlled via React state (value prop).
Uncontrolled Components: Value is accessed directly from the DOM using ref.

Public folder

Images are placed in public folder and referenced via relative paths


// Assume image is placed at public/images/logo.png
function Logo() {
  return Logo;
}


React Hooks

Lifecycle features for a functional component.

Initial Phase - when a component is being created
Mounting Phase - inserted into the DOM.
Updating Phase - when a component's state or props change, causing it to re-render.
Unmounting Phase - Phase-when a component is being removed from the DOM.

Lifecycle methods:
React lifecycle methods allow you to hook into different phases of a component's lifecycle.

Intial render
getDefaultProps()
getInitialState()
componentWillMount()
render()
componentDidMount()

State change
shouldComponentUpdate()
componentWillUpdate()
render()
componentDidUpdate()

Props change
componentWillReceiveProps()
shouldComponentUpdate()
componentWillUpdate()
render()
componentDidUpdate()

Unmount
componentWillUnmount()

Prop drilling

Prop drilling is a pattern in React where data is passed from a parent component to a deeply nested child component through intermediary components.

Hooks

Hooks—functions starting with use—can only be called at the top level of your components or your own Hooks.

useState()

The useState hook is used to manage state in functional components.


import React, { useState } from 'react';

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

  return (
    

Count: {count}

); } export default Counter;

useEffect

The useEffect hook in React is used to handle side effects in functional components.


import React, { useEffect } from 'react';

useEffect(() => {
  // side effect code here
}, [dependencies]);


Dependency Array
No Dependency Array: The effect runs after every render.
Empty Dependency Array: The effect runs only once, after the initial render
Specific Dependencies: The effect runs only when one or more of the specified dependencies change.

useParams

It is used to extract parameters from the URL.


import { useParams } from 'react-router-dom';

function ProductDetail() {
const { id } = useParams(); // Extracts the id parameter from the URL

return

Product ID: {id}
;
}




useNavigate

It is used to programmatically navigate between routes. It replaces useHistory from earlier versions.


import { useNavigate } from 'react-router-dom';

function HomeButton() {
const navigate = useNavigate();

return (

);
}




useRef

The useRef hook is used to create mutable references that persist across renders. It can be used to access DOM elements directly.


import React, { useRef } from 'react';

function FocusInput() {
const inputRef = useRef(null);

const focusInput = () => {
inputRef.current.focus();
};

return (





);
}

export default FocusInput;




ReactDOM.render

The ReactDOM.render method is used to render a React element (or a component) into a DOM container.


import React from 'react';
import ReactDOM from 'react-dom';
import MyComponent from './MyComponent';

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




render()

In the context of React class components, the render() method is a lifecycle method that must be implemented. It describes what the UI should look like for the component.


import React from 'react';

class MyComponent extends React.Component {
render() {
return (


Hello, World!



);
}
}

export default MyComponent;




Normal DOM

It is a programming interface for web documents.
Direct manipulation of the DOM can be slow and expensive because it involves updating the entire structure of the web page.

Virtual DOM

It is a concept implemented by libraries like React, where a virtual representation of the real DOM is kept in memory and synced with the real DOM by a library such as ReactDOM. When the state of an application changes, the Virtual DOM is updated first, instead of the real DOM.
The virtual DOM employs a reconciliation algorithm to calculate the differences between the previous virtual DOM and the current virtual DOM, and then applies the necessary changes to the real DOM

Working of Virtual DOM:

1) When a component is first rendered, a virtual DOM tree is created based on the component's render output.
2) When the state of a component changes, a new virtual DOM tree is created.
3) The new virtual DOM tree is compared (or "diffed") with the previous virtual DOM tree to determine what has changed.
4) Only the parts of the DOM that have changed are updated in the real DOM. This process is called "reconciliation".
5) Changes are batched and applied in a single pass to minimize the number of updates to the real DOM, which improves performance

CSR

  1. A user clicks a link to visit a webpage.
  2. The browser sends an HTTP request to the server for the requested page.
  3. The server responds with a minimal HTML document, often including references to JavaScript files (like bundled JavaScript code) and CSS files. The HTML document typically contains a
    element with an ID where the React app (or other JavaScript frameworks) will be rendered.
  4. Once the browser receives the HTML, it starts loading and executing the JavaScript files specified in the HTML. This file contains the code for rendering the user interface and handling user interactions.
  5. Stay Connected!
    If you enjoyed this post, don’t forget to follow me on social media for more updates and insights:

    Twitter: madhavganesan
    Instagram: madhavganesan
    LinkedIn: madhavganesan

版本聲明 本文轉載於:https://dev.to/madgan95/introduction-to-react-library--4k5i?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>
  • HTML 格式標籤
    HTML 格式標籤
    HTML 格式化元素 **HTML Formatting is a process of formatting text for better look and feel. HTML provides us ability to format text without us...
    程式設計 發佈於2024-12-29
  • 如何在 PHP 中組合兩個關聯數組,同時保留唯一 ID 並處理重複名稱?
    如何在 PHP 中組合兩個關聯數組,同時保留唯一 ID 並處理重複名稱?
    在 PHP 中組合關聯數組在 PHP 中,將兩個關聯數組組合成一個數組是常見任務。考慮以下請求:問題描述:提供的代碼定義了兩個關聯數組,$array1 和 $array2。目標是建立一個新陣列 $array3,它合併兩個陣列中的所有鍵值對。 此外,提供的陣列具有唯一的 ID,而名稱可能重疊。要求是建...
    程式設計 發佈於2024-12-29
  • 大批
    大批
    方法是可以在物件上呼叫的 fns 數組是對象,因此它們在 JS 中也有方法。 slice(begin):將陣列的一部分提取到新數組中,而不改變原始數組。 let arr = ['a','b','c','d','e']; // Usecase: Extract till index ...
    程式設計 發佈於2024-12-29
  • 插入資料時如何修復「常規錯誤:2006 MySQL 伺服器已消失」?
    插入資料時如何修復「常規錯誤:2006 MySQL 伺服器已消失」?
    插入記錄時如何解決「一般錯誤:2006 MySQL 伺服器已消失」介紹:將資料插入MySQL 資料庫有時會導致錯誤「一般錯誤:2006 MySQL 伺服器已消失」。當與伺服器的連線遺失時會出現此錯誤,通常是由於 MySQL 配置中的兩個變數之一所致。 解決方案:解決此錯誤的關鍵是調整wait_tim...
    程式設計 發佈於2024-12-29
  • 儘管程式碼有效,為什麼 POST 請求無法擷取 PHP 中的輸入?
    儘管程式碼有效,為什麼 POST 請求無法擷取 PHP 中的輸入?
    解決PHP 中的POST 請求故障在提供的程式碼片段中:action=''而非:action="<?php echo $_SERVER['PHP_SELF'];?>";?>"檢查$_POST陣列:表單提交後使用 var_dump 檢查 $_POST 陣列的內...
    程式設計 發佈於2024-12-29
  • Bootstrap 4 Beta 中的列偏移發生了什麼事?
    Bootstrap 4 Beta 中的列偏移發生了什麼事?
    Bootstrap 4 Beta:列偏移的刪除和恢復Bootstrap 4 在其Beta 1 版本中引入了重大更改柱子偏移了。然而,隨著 Beta 2 的後續發布,這些變化已經逆轉。 從 offset-md-* 到 ml-auto在 Bootstrap 4 Beta 1 中, offset-md-*...
    程式設計 發佈於2024-12-29
  • 在 Go 中使用 WebSocket 進行即時通信
    在 Go 中使用 WebSocket 進行即時通信
    构建需要实时更新的应用程序(例如聊天应用程序、实时通知或协作工具)需要一种比传统 HTTP 更快、更具交互性的通信方法。这就是 WebSockets 发挥作用的地方!今天,我们将探讨如何在 Go 中使用 WebSocket,以便您可以向应用程序添加实时功能。 在这篇文章中,我们将介绍: WebSoc...
    程式設計 發佈於2024-12-29
  • 如何在 React 中有條件地應用類別屬性?
    如何在 React 中有條件地應用類別屬性?
    在React 中有條件地應用類別屬性在React 中,根據從父組件傳遞的props 來顯示或隱藏元素是很常見的。為此,您可以有條件地應用 CSS 類別。然而,當使用語法 {this.props.condition ? 'show' : 'hidden'} 直接在字串中...
    程式設計 發佈於2024-12-28
  • 如何在Java中執行系統命令並與其他應用程式互動?
    如何在Java中執行系統命令並與其他應用程式互動?
    Java 中運行進程在 Java 中,啟動進程的能力是執行系統命令和與其他應用程式互動的關鍵功能。為了啟動一個流程,Java提供了一個相當於.Net System.Diagnostics.Process.Start方法。 解決方案:取得本地路徑對於執行至關重要Java 中的程序。幸運的是,Java ...
    程式設計 發佈於2024-12-28
  • 如何在 C++ 中建立多行字串文字?
    如何在 C++ 中建立多行字串文字?
    C 中的多行字串文字 在 C 中,定義多行字串文字並不像 Perl 等其他語言那麼簡單。但是,您可以使用一些技術來實現此目的:連接字串文字一種方法是利用 C 中相鄰字串文字由編譯器連接的事實。將字串分成多行,您可以建立單一多行字串:const char *text = "This te...
    程式設計 發佈於2024-12-28
  • 如何準確地透視具有不同記錄的資料以避免遺失資訊?
    如何準確地透視具有不同記錄的資料以避免遺失資訊?
    有效地透視不同記錄透視查詢在將資料轉換為表格格式、實現輕鬆資料分析方面發揮著至關重要的作用。但是,在處理不同記錄時,資料透視查詢的預設行為可能會出現問題。 問題:忽略不同值考慮下表:------------------------------------------------------ | Id...
    程式設計 發佈於2024-12-27
  • 為什麼 C 和 C++ 忽略函式簽章中的陣列長度?
    為什麼 C 和 C++ 忽略函式簽章中的陣列長度?
    將陣列傳遞給C 和C 中的函數問題:為什麼C和C 編譯器允許在函數簽章中宣告數組長度,例如int dis(char a[1])(當它們不允許時)強制執行? 答案:C 和C 中用於將數組傳遞給函數的語法是歷史上的奇怪現象,它允許將指針傳遞給第一個元素詳細說明:在C 和C 中,數組不是透過函數的引用傳遞...
    程式設計 發佈於2024-12-26
  • 如何刪除 MySQL 中的重音符號以改進自動完成搜尋?
    如何刪除 MySQL 中的重音符號以改進自動完成搜尋?
    在MySQL 中刪除重音符號以實現高效的自動完成搜尋管理大型地名資料庫時,確保準確和高效至關重要資料檢索。使用自動完成功能時,地名中的重音可能會帶來挑戰。為了解決這個問題,一個自然的問題出現了:如何在 MySQL 中刪除重音符號以改善自動完成功能? 解決方案在於為資料庫列使用適當的排序規則設定。透過...
    程式設計 發佈於2024-12-26
  • 如何在MySQL中實作複合外鍵?
    如何在MySQL中實作複合外鍵?
    在 SQL 中實作複合外鍵一個常見的資料庫設計涉及使用複合鍵在表之間建立關係。複合鍵是多個列的組合,唯一標識表中的記錄。在這個場景中,你有兩個表,tutorial和group,你需要將tutorial中的複合唯一鍵連結到group中的欄位。 根據MySQL文檔,MySQL支援外鍵對應到複合鍵。但是,...
    程式設計 發佈於2024-12-26
  • 為什麼我的 JComponent 隱藏在 Java 的背景圖片後面?
    為什麼我的 JComponent 隱藏在 Java 的背景圖片後面?
    調試背景圖像隱藏的JComponent在Java 應用程式中使用JComponent(例如JLabels)時,必須確保正確的行為和可見度。如果遇到組件隱藏在背景圖像後面的問題,請考慮以下方法:1。正確設定組件透明度:確保背景面板是透明的,以允許底層組件透過。使用setOpaque(false)方法來...
    程式設計 發佈於2024-12-26

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3