”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > React 库简介:)

React 库简介:)

发布于2024-11-08
浏览:459

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]删除
最新教程 更多>
  • 混淆技术真的可以保护可执行文件免受逆向工程的影响吗?
    混淆技术真的可以保护可执行文件免受逆向工程的影响吗?
    保护可执行文件免遭逆向工程:解决方案有限的挑战保护代码免遭未经授权的逆向工程是开发人员持续关注的问题,尤其是当它包含敏感信息。虽然已经提出了各种方法,但重要的是要承认完全防止逆向工程实际上是不可能的。常见混淆技术用户建议的策略,例如代码注入、混淆和自定义启动例程的目的是使反汇编变得不那么简单。然而,...
    编程 发布于2024-11-08
  • 掌握 Laravel 中的 Eloquent where 条件
    掌握 Laravel 中的 Eloquent where 条件
    Laravel 的 Eloquent ORM(对象关系映射)是其突出的功能之一,提供了一种与数据库交互的强大而富有表现力的方式。 Eloquent 提供的一项基本功能是方法,它允许开发人员高效、直观地过滤查询。在本文中,我们将深入研究 where 条件,探索其各种形式和实际用例。 ...
    编程 发布于2024-11-08
  • 在 Gmail 的 Chrome 12+ 更新中如何从剪贴板粘贴图像?
    在 Gmail 的 Chrome 12+ 更新中如何从剪贴板粘贴图像?
    将剪贴板中的图像粘贴到 Gmail:Chrome 12 中的操作方法 Google 宣布能够将剪贴板中的图像直接粘贴到 Gmail使用 Chrome 12 的 Gmail 引发了人们对其底层机制的好奇。尽管使用了最新的 Chrome 版本,一些用户仍然无法找到有关如何在 Webkit 中实现此增强功...
    编程 发布于2024-11-08
  • JavaScript 演示场景竞赛 - JS 版
    JavaScript 演示场景竞赛 - JS 版
    JS1024 于 2024 年回归! 准备好迎接激动人心的挑战! JS1024 回归,通过在 JavaScript、HTML 或 GLSL 中创建令人惊叹的演示(全部在 1024 字节限制内),将开发人员推向极限。无论您是经验丰富的编码员还是新手,这都是您展示创造力和技术技能的机会...
    编程 发布于2024-11-08
  • 第九届 TCmeeting 的更新
    第九届 TCmeeting 的更新
    议程上有几个项目,本文重点介绍第 104 次 TC39 会议 [2024 年 10 月 8 日至 10 日] 的功能提案及其进展。 第一阶段: 表示度量:建议在 JavaScript 中使用适当的单位格式化和表示度量。 Immutable ArrayBuffers:添加 ArrayB...
    编程 发布于2024-11-08
  • 如何使用 CSS 在图像地图上实现鼠标悬停效果?
    如何使用 CSS 在图像地图上实现鼠标悬停效果?
    使用 CSS 设置图像地图鼠标悬停样式创建交互式网页时,通常需要包含具有可单击区域的图像。通常,这是使用图像映射来实现的。然而,事实证明,在鼠标悬停时设置这些区域的样式以提供额外的交互性是难以实现的。过去,尝试使用 CSS 设置这些区域的样式所取得的成功有限,如提供的示例所示:<img src...
    编程 发布于2024-11-08
  • 升级您的前端游戏:无头和静态未来的学习框架
    升级您的前端游戏:无头和静态未来的学习框架
    前端领域正在以惊人的速度发展。忘掉笨重、单一的网站吧——未来属于无头 CMS 和静态网站生成器 (SSG)。这些时尚的强大功能提供了无与伦比的速度、灵活性和安全性,但征服它们需要使用正确的工具。 为了利用他们的力量,开发人员正在转向 Next.js 和 Gatsby,这两个尖端的前端框架塑造了我们...
    编程 发布于2024-11-08
  • 如何修复 PyGame 动画闪烁:故障排除和解决方案
    如何修复 PyGame 动画闪烁:故障排除和解决方案
    PyGame 动画闪烁:故障排除和解决方案运行 PyGame 程序时,您可能会遇到动画闪烁的问题。这可能会令人沮丧,特别是如果您不熟悉使用该框架。PyGame 中动画闪烁的根本原因通常是多次调用 pygame.display.update()。不应在应用程序循环中的多个点更新显示,而应仅在循环结束时...
    编程 发布于2024-11-08
  • JavaScript 中的声明式编程与命令式编程
    JavaScript 中的声明式编程与命令式编程
    当谈到编程方法时,经常会出现两种常见的方法:声明式编程和命令式编程。每个都有其优点和理想的用例,尤其是在 JavaScript 中。让我们通过一些例子来探讨这两种风格。 命令式编程:告诉计算机如何做 命令式编程就像给出一组详细的指令。你告诉计算机如何一步步达到特定的结果。将其视为指导...
    编程 发布于2024-11-08
  • 掌握 NestJS 中的数据验证:类验证器和类转换器的完整指南
    掌握 NestJS 中的数据验证:类验证器和类转换器的完整指南
    Introduction In the fast-paced world of development, data integrity and reliability are paramount. Robust data validation and efficient handl...
    编程 发布于2024-11-08
  • 有多少 Python 包的版本控制正确?
    有多少 Python 包的版本控制正确?
    前几天,当我研究Python包中的漏洞数据库时,我意识到其中的一些包版本无法轻松解析并与其他版本字符串进行比较,因为它们不遵守Python 版本控制 - 旧的 PEP 440 或取代它的版本说明符规范。所以我开始想知道这种情况有多普遍。 Python 包索引上有多少包实际上具有有效版本? 显而易见的...
    编程 发布于2024-11-08
  • 如何在 Web 应用程序中有效地对 Ajax 请求进行排序?
    如何在 Web 应用程序中有效地对 Ajax 请求进行排序?
    排序 Ajax 请求在许多 Web 应用程序中,通常会遇到需要迭代集合并对每个元素发出 Ajax 请求的情况。虽然利用异步请求来避免浏览器冻结很诱人,但有效管理这些请求可以防止服务器过载和其他潜在问题。jQuery 1.5 对于 jQuery 1.5 及更高版本,$. ajaxQueue() 插件提...
    编程 发布于2024-11-08
  • JavaScript 中“%”运算符的作用是什么?
    JavaScript 中“%”运算符的作用是什么?
    揭开 JavaScript 中 % 运算符的本质JavaScript 中神秘的 % 符号被称为模运算符。它在数学运算中发挥着关键作用,它返回一个操作数除以另一个操作数后的余数。模运算符通常表示如下:var1 % var2其中var1 和 var2 代表操作数。例如,如果我们有表达式 12 % 5,结...
    编程 发布于2024-11-08
  • 检测过时的描述
    检测过时的描述
    开发人员文档通常在每个文件中包含说明。这些描述可能会过时,导致混乱和不正确的信息。为了防止这种情况,您可以使用一些 AI 和 GenAIScript 自动检测文档中过时的描述。 Markdown 和 frontmatter 许多文档系统使用 markdown 格式来编写文档,并使用“...
    编程 发布于2024-11-08
  • Java性能优化技术
    Java性能优化技术
    你好 ? 您可以找到有关 Java 性能优化技术 的完整文章 1. 概述 优化您的代码性能对于您的个人资料的成功至关重要。您是否知道 Akamai 的研究发现,如果页面加载时间超过 3 秒,57% 的在线消费者就会放弃网站?在这篇文章中,您将学习如何优化 Java 代码并提高代码性能...
    编程 发布于2024-11-08

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3