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

React 函式庫簡介:)

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

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]刪除
最新教學 更多>
  • 使用 .EJS 範本配置 Express
    使用 .EJS 範本配置 Express
    通常,我使用經典的入門版。 Expressjs.com const express = require('express') const app = express() const port = 3000 app.set('view engine', 'ejs') app.use(express....
    程式設計 發佈於2024-11-08
  • 如何將自訂字體新增至 Tailwind - 對於網頁和本機下載的字體
    如何將自訂字體新增至 Tailwind - 對於網頁和本機下載的字體
    创建 Web 应用程序时,包含您喜欢的字体就像锦上添花。字体增强文本效果,使网站更具吸引力,并提供更好的用户体验。设计师和开发人员对某些字体又爱又恨,使用默认字体可能会限制他们的创造力。添加自定义字体使开发人员可以自由地将外部字体添加到他们的应用程序中。 先决条件 在本教程中,我强烈...
    程式設計 發佈於2024-11-08
  • JavaScript 柯里化的詳細討論
    JavaScript 柯里化的詳細討論
    Currying হলো একটি ফাংশনাল প্রোগ্রামিং কৌশল যেখানে একটি ফাংশন একাধিক আর্গুমেন্ট নেওয়ার পরিবর্তে একটি একক আর্গুমেন্ট গ্রহণ করে এবং একটি নতুন ফাংশন রিটা...
    程式設計 發佈於2024-11-08
  • 了解 Python 裝飾器:深入探討
    了解 Python 裝飾器:深入探討
    Python 裝飾器是強大的工具,允許我們修改或增強函數或方法的行為。常見用例包括日誌記錄、授權等。 然而,當被要求定義裝飾器時,許多人可能會說, 它是函數的包裝器。 雖然這在技術上是正確的,但幕後還發生了更多事情。 剖析一個簡單的裝飾器 讓我們探討一個簡單的例子: def my_decora...
    程式設計 發佈於2024-11-08
  • 課程計畫:年級學生 Python 基礎知識(初級)
    課程計畫:年級學生 Python 基礎知識(初級)
    客观的: 在本课程结束时,学生将对 Python 编程有基本的了解,包括变量、基本数据类型、循环和函数。他们将使用 Python 创建简单的程序,运用逻辑思维和解决问题的技能。 持续时间:6 节课 第 1 课:Python 简介和设置 目标:让学生熟...
    程式設計 發佈於2024-11-08
  • 如何在 Java 中正確複製二維數組以保留修改?
    如何在 Java 中正確複製二維數組以保留修改?
    透過複製保留二維數組修改在 Java 中,建立物件副本時,了解引用分配行為至關重要。在給定的場景中,定義了兩個名為 current 和 old 的二維數組,以及複製內容的方法。 old() 方法將 current 陣列指派給 old 。然而,這只是將引用傳輸到記憶體中的相同數組。當 current ...
    程式設計 發佈於2024-11-08
  • 使用 JavaScript 創建令人著迷的粒子動畫
    使用 JavaScript 創建令人著迷的粒子動畫
    這就是我們要創建的,將滑鼠移到粒子上即可查看效果。 在本文中,我將引導您完成使用 JavaScript 和 HTML5 畫佈建立迷人粒子動畫的過程。該專案不僅增強了網頁的美觀性,而且還是深入研究一些有趣的編碼概念的絕佳機會。讓我們開始吧! 項目概況 動畫的特點是粒子圍繞中心點以圓...
    程式設計 發佈於2024-11-08
  • 使用 JavaScript 釋放大型語言模型的力量:實際應用程式
    使用 JavaScript 釋放大型語言模型的力量:實際應用程式
    In recent years, Large Language Models (LLMs) have revolutionized how we interact with technology, enabling machines to understand and generate human-...
    程式設計 發佈於2024-11-08
  • Bootstrap 與 Tailwind 整合:Pro 與 Contro | Bootstrap 和 Tailwind:優點和缺點
    Bootstrap 與 Tailwind 整合:Pro 與 Contro | Bootstrap 和 Tailwind:優點和缺點
    简介 |介绍 意大利语: 本文有意大利语和英语版本。向下滚动查看英文版本。 英语: 本文有意大利语和英语版本。向下滚动查看英文版本。 意大利语版 Bootstrap 和 Tailwind 集成简介 近年来,Bootstrap和Tailwind CSS已经成为前端开发最流行的两个框架。 Boot...
    程式設計 發佈於2024-11-08
  • 我們如何使用 Gin 框架來增強 Go 應用程式中的錯誤處理?
    我們如何使用 Gin 框架來增強 Go 應用程式中的錯誤處理?
    更好的錯誤處理問題在Go應用程式中,我們如何透過定義自訂錯誤類型(例如appError和實現自定義處理程序來捕獲錯誤並將其寫入回應中?正常的流程邏輯。 ))建立錯誤中間件:func JSONAppErrorReporter() gin.HandlerFunc { 返回 func(c *gin...
    程式設計 發佈於2024-11-08
  • DOM API 終極指南
    DOM API 終極指南
    // Selecting Elements: document is not the real DOM element. document.documentElement; // Select the entire page document.head; // Select the head doc...
    程式設計 發佈於2024-11-08
  • Python 中的實例方法與類別方法:什麼時候應該使用“self”和“cls”?
    Python 中的實例方法與類別方法:什麼時候應該使用“self”和“cls”?
    深入研究類別和實例方法的細微差別:Beyond Self 與ClsPython 增強提案(PEP) 8 建議使用“self”作為實例方法中的第一個參數,「cls」作為類別方法中的第一個參數。這種差異源自於這些方法在處理實例和類別時所扮演的不同角色。 實例方法:自我優勢實例方法在實例的實例上呼叫班級。...
    程式設計 發佈於2024-11-08
  • Node.js 傻瓜指南 - MongoDB 和 Fastify
    Node.js 傻瓜指南 - MongoDB 和 Fastify
    O que é Node.js? Node.js, uma plataforma construída sobre o motor de JavaScript V8 do Google Chrome, revolucionou o desenvolvimento backend n...
    程式設計 發佈於2024-11-08
  • 如何使用 Joda Time 將日期字串解析為 DateTime 物件並避免「無效格式」錯誤?
    如何使用 Joda Time 將日期字串解析為 DateTime 物件並避免「無效格式」錯誤?
    使用Joda Time 將日期字串解析為DateTime 物件處理日期和時間資料時,通常需要轉換日期作為字串儲存到結構化物件中以便進一步處理。 Joda Time 庫提供了一套全面的工具,用於處理 Java 中的日期和時間操作。 一個常見任務是將日期字串轉換為 DateTime 物件。但是,如果字串...
    程式設計 發佈於2024-11-08
  • 如何解決 PHP 中的「每個引號前都有斜線」問題?
    如何解決 PHP 中的「每個引號前都有斜線」問題?
    理解「引號前的斜槓」問題在某些情況下,PHP網頁可能會遇到提交表單資料導致添加一個每個雙引號前都有反斜線。此問題是由稱為“魔術引號”的伺服器配置功能引起的。 啟用魔術引號後,PHP 在向資料庫或表單提交發送或從資料庫或表單提交接收某些字符時,會自動轉義某些字符,包括雙引號。雖然這可以透過轉義惡意引號...
    程式設計 發佈於2024-11-08

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

Copyright© 2022 湘ICP备2022001581号-3