type
status
date
slug
summary
tags
category
icon
password

React

Set up the development environment:cra(create-react-app) Command: npx create-react-app [project_name] cd to the auto-created fold: cd [project_name] Run the project: npm start
notion image
Initial page of project package.json dependencies: Dependent packages:
notion image
scripts: Executable commands:
notion image
build - for package
src source code:
Keep index.js and app.js, delete everything else.
App.js keep the basic code:
notion image
Index.js keep the basic code:
notion image
To see how to start a new project in detail:
 
JSX: The abbreviation for JavaScript and XML (HTML). It is a way to write HTML template structures in JS code and is used to create UI templates in React. The following part is the declarative template syntax from JSX to HTML, along with the programmable capabilities of JS.
notion image
 
Parsing of JSX (which is not recognized by the browser itself):
notion image
notion image
 
Using JS expressions in JSX:
Curly brace syntax
Four basic usages (as shown in the diagram).
if statements and switch
statements are not expressions and cannot appear inside curly braces.
notion image
 
Implementing list rendering in JSX:
Map method
- Return the same structure as the one being looped through.
Notes
- Add a unique key value, either a string or a number (e.g., ID).
Purpose of the key
: It's used internally by the React framework to improve update performance.
notion image
 
JSX Conditional Rendering:
If
is true - "Blair"
If
is false - "Please log in."
notion image
 
Implementing complex conditional rendering in JSX:
Requirement:
The list needs to adapt to three cases based on the article status: single image, three images, and no image.
Solution:
Custom function + if statement.
notion image
 
Basic Event Binding in React
Syntax:
Overall, it follows camelCase naming convention.
notion image
notion image
 
Passing Custom Parameters / Custom + e:
notion image
notion image
 
 
React Component: A component is a part of the user interface that can have its own logic and appearance. Components can be nested within each other and can also be repeated multiple times.
<Root>
<Header>
<Main> <Aside>
In React, a component is a function with an uppercase initial letter that contains the component's logic and UI. To render a component, you simply write it as a tag.
Defining a Component:
Return the corresponding software/root component.
It can be defined using either function or const
- the function name should start with an uppercase letter.
notion image
 
Basic Usage of useState:
is a React Hook (function) that allows us to add a state variable to a component, thereby controlling the rendering result that affects the component.
Essence:
Unlike ordinary JS variables, when a state variable changes, the component's UI view also updates accordingly (data-driven view).
notion image
 
State Modification Rules
State is immutable: In React, state is considered read-only. We should always replace it rather than modify it. Directly modifying the state will not trigger a view update.
notion image
 
Modifying Object State
Rule: For state variables of object type, you should always pass a brand-new object to the set method to make modifications.
notion image
 

Component Styling

Basic style control for React components can be done in two ways:
  1. Inline styles (not recommended)
notion image
  1. Control with class names
notion image
 

Comment Project

commentProject
itsBlairWUpdated Aug 8, 2024

Requirements:

  1. Render a comment list.
  1. Implement comment deletion.
      • Only the user's own comments should display the delete button.
        • Approach: Conditional rendering.
      • Clicking the delete button should remove the current comment from the list.
        • Get the current item's ID and use it as a condition to filter the comment list.
  1. Render navigation tabs and implement highlighting.
  1. Implement sorting functionality for the comment list.

Core Concepts:

  1. Use useState to maintain the comment list.
  1. Use the map method to iterate and render the list data (remember to add a key).
      • Rendering Tabs and Implementing Highlight:
        • Requirement: Highlight the tab that is clicked.
        • Core Idea: Record the type (unique identifier) of the clicked tab and match it with each item's type during iteration. Highlight the matched item with a class name.

Sorting Functionality

  • Requirement: Clicking "Newest" should sort the comment list by creation time in descending order (newest first). Clicking "Hottest" should sort by the number of likes (most likes first).

Classname Optimization

classname is a simple JavaScript library that allows for dynamic class name control based on conditions.
Example:
notion image
 
Issue: String Concatenation for Class Names is Not Intuitive and Error-Prone
Correction:
'nav-item': Static class name
active: type === item.type: Dynamic class name, where the key represents the class name to be controlled and the value represents the condition. The class name is applied when the condition is true.
classnames library:
active: type === item.type: 动态类名,key表示要控制的类名,value表示条件,true的时候显示类名
classnames库:
 

Controlled Form Binding

Concept: Use the state of a React component (useState) to control the state of a form.
React => State is bound to the input's value property <input/> (State) <= Set the latest value from the input to the state (value)
  1. Prepare a React state value:
    1. Bind the state through the value property and bind the function for state synchronization through the onChange property:
      notion image
      notion image
       

      Getting DOM in React

      Fixed Method: Use the useRef hook, which involves two steps:
      1. Create a ref object using useRef and bind it in JSX:
        1. When the DOM is available, access the DOM object through inputRef.current:
          notion image
           

          Back to Comment Project

          Post a Comment:
          1. Get the comment content.
          1. Click the publish button to post the comment.
          ID Handling and Time Handling:
          1. The rpid requires a unique random number ID: https://github.com/uuidjs/uuid.
          1. The ctime requires generating a fixed format based on the current time - day.js.
          Clear Content and Refocus:
          1. Clear the content - Set the state controlling the input box's value to an empty string.
          1. Refocus - Get the input element and call the focus method.
           

          Component communication

          Component communication refers to the data transmission between components. Depending on the nesting relationship of the components, there are different communication methods.
          Parent to Child - Basic Implementation:
          1. Parent Component Passing Data: Bind attributes on the child component's tag.
          1. Child Component Receiving Data: The child component receives the data through the props parameter.
          notion image
           
          1. props can pass any type of data: ◦ Numbers ◦ Strings ◦ Booleans ◦ Arrays ◦ Objects ◦ Functions ◦ JSX
          notion image
           
          1. props are read-only objects:
              • The child component can only read data from props, and only the parent component can modify them.
          Special Prop - children:
          • Scenario: When we nest content within a child component's tag, the parent component automatically receives this content in a prop named children.
          notion image
          notion image
           
          Child to Parent Communication:
          • Core Idea: The child component calls a function from the parent component and passes arguments to it.
          notion image
           
          Using State Lifting to Achieve Sibling Component Communication:
          • Implementation Idea: Utilize the "state lifting" mechanism to transfer data between sibling components through the parent component.
          1. Component A - APP:
          notion image
           
          2. APP-B
          notion image
          State Lifting: Elevate the state to the common parent component.
           
          Using Context Mechanism for Cross-Level Component Communication:
          1. Use the createContext method to create a context object Ctx (you can name it anything).
          1. In the top-level component (App), provide data using the Ctx.Provider component.
          1. In the lower-level component (B), consume the data using the useContext hook.
          notion image
           

          Understanding the Concept of useEffect

          useEffect is a React Hook function used to create operations in React components that are triggered by the component's rendering itself, rather than by an event. These operations can include tasks such as sending AJAX requests, modifying the DOM, etc.
          Explanation: The entire process does not involve any user events. After the component has rendered, it needs to fetch data from the server, which is an operation triggered solely by the rendering process.

          Basic Usage:

          Requirement: After the component has rendered, immediately fetch the channel list data from the server and display it on the page.
          Syntax: useEffect(() => {}, [])
          • Parameter 1: Callback function -> Side-effect function, where you can place the operations you want to execute.
          • Parameter 2: Dependency array (optional). Place dependencies in the array. Different dependencies affect the execution of the first parameter function. When it's an empty array, the side-effect function will only execute once after the component has rendered.
          notion image
           

          Explanation of useEffect Dependency Parameter

          • Dependencies: The conditions under which the side-effect function executes.
            • Dependencies
              Execution Timing of Side-Effect Function
              No dependencies
              Executes on initial render + every update of the component
              Empty array []
              Executes only once on initial render
              Specific dependencies
              Executes on initial render + whenever specified dependencies change
          notion image
           

          Clearing Side Effects with useEffect

          Clean up the side effects created in useEffect when the component unmounts (e.g., a timer).
          Note: The most common timing for execution is automatically when the component unmounts.
          notion image
           

          Custom Hook function:

          Concept: A custom Hook is a function that starts with
          By creating a custom Hook, you can encapsulate and reuse logic.
          notion image
           
          Rules for using React Hooks:
          1. Hooks can only be called inside components or other custom Hook functions.
          1. Hooks can only be used at the top level of a component or Hook, and cannot be called inside if statements, forloops, or other functions.
          notion image
          notion image
          notion image
           

          Comment Project

          Optimization Requirements:
          1. Retrieve and render the comment list using an API.
          Fetching the Comment List via API:
          1. Use json-server to Mock API Service:
              • json-server is a tool that quickly simulates API services using a .json file as the data source.
              • Axios is a widely used front-end request library.
          1. Use useEffect to Fetch Data:
              • Use the useEffect hook to call the API and retrieve data.
          notion image
           
          Optimization Requirements:
          1. Encapsulate Data Fetching Logic with a Custom Hook:
          notion image
          notion image
           
          Abstract Each Comment into a Separate Component
          Encapsulate the Comment Item Component:
          • Principle of Abstraction: The App component, as a "smart" component, is responsible for data fetching. The Itemcomponent, as a "UI" component, is responsible for rendering the data.
           
          • Author:Blair Wang
          • URL://article/react
          • Copyright:All articles in this blog, except for special statements, adopt BY-NC-SA agreement. Please indicate the source!
          Web Scraping with PythonFigma
          Loading...
          Blair Wang
          Blair Wang
          Love& Live
          Announcement
          🎉My Personal Website Published🎉
          -- Thanks for your Tour ---