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

React 库简介:)

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

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
  • 如何修复 macOS 上 Django 中的“配置不正确:加载 MySQLdb 模块时出错”?
    如何修复 macOS 上 Django 中的“配置不正确:加载 MySQLdb 模块时出错”?
    MySQL配置不正确:相对路径的问题在Django中运行python manage.py runserver时,可能会遇到以下错误:ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Library/Python/2.7/site-...
    编程 发布于2024-12-29
  • 如何使用 MySQL 查找今天生日的用户?
    如何使用 MySQL 查找今天生日的用户?
    如何使用 MySQL 识别今天生日的用户使用 MySQL 确定今天是否是用户的生日涉及查找生日匹配的所有行今天的日期。这可以通过一个简单的 MySQL 查询来实现,该查询将存储为 UNIX 时间戳的生日与今天的日期进行比较。以下 SQL 查询将获取今天有生日的所有用户: FROM USERS ...
    编程 发布于2024-12-29
  • 大批
    大批
    方法是可以在对象上调用的 fns 数组是对象,因此它们在 JS 中也有方法。 slice(begin):将数组的一部分提取到新数组中,而不改变原始数组。 let arr = ['a','b','c','d','e']; // Usecase: Extract till index p...
    编程 发布于2024-12-29
  • 插入数据时如何修复“常规错误:2006 MySQL 服务器已消失”?
    插入数据时如何修复“常规错误:2006 MySQL 服务器已消失”?
    插入记录时如何解决“一般错误:2006 MySQL 服务器已消失”介绍:将数据插入 MySQL 数据库有时会导致错误“一般错误:2006 MySQL 服务器已消失”。当与服务器的连接丢失时会出现此错误,通常是由于 MySQL 配置中的两个变量之一所致。解决方案:解决此错误的关键是调整wait_tim...
    编程 发布于2024-12-29
  • 除了“if”语句之外:还有哪些地方可以在不进行强制转换的情况下使用具有显式“bool”转换的类型?
    除了“if”语句之外:还有哪些地方可以在不进行强制转换的情况下使用具有显式“bool”转换的类型?
    无需强制转换即可上下文转换为 bool您的类定义了对 bool 的显式转换,使您能够在条件语句中直接使用其实例“t”。然而,这种显式转换提出了一个问题:“t”在哪里可以在不进行强制转换的情况下用作 bool?上下文转换场景C 标准指定了四种值可以根据上下文转换为的主要场景bool:语句:if、whi...
    编程 发布于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 = "...
    编程 发布于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

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

Copyright© 2022 湘ICP备2022001581号-3