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
Initial page of project
package.json
dependencies:
Dependent packages:
scripts:
Executable commands:
build - for package
src source code:
Keep
index.js
and app.js
, delete everything else.App.js keep the basic code:
Index.js keep the basic code:
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.
Parsing of JSX (which is not recognized by the browser itself):
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.
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.
JSX Conditional Rendering:
If
is true - "Blair"
If
is false - "Please log in."
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.
Basic Event Binding in React
Syntax:
Overall, it follows camelCase naming convention.
Passing Custom Parameters / Custom + e:
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.
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).
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.
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.
Component Styling
Basic style control for React components can be done in two ways:
- Inline styles (not recommended)
- Control with class names
Comment Project
commentProject
itsBlairW • Updated Aug 8, 2024
Requirements:
- Render a comment list.
- 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.
- Render navigation tabs and implement highlighting.
- Implement sorting functionality for the comment list.
Core Concepts:
- Use
useState
to maintain the comment list.
- 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:
Issue: String Concatenation for Class Names is Not Intuitive and Error-Prone
Correction:
'nav-item'
: Static class nameactive: 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)- Prepare a React state value:
- Bind the state through the
value
property and bind the function for state synchronization through theonChange
property:
Getting DOM in React
Fixed Method: Use the
useRef
hook, which involves two steps:- Create a ref object using
useRef
and bind it in JSX:
- When the DOM is available, access the DOM object through
inputRef.current
:
Back to Comment Project
Post a Comment:
- Get the comment content.
- Click the publish button to post the comment.
ID Handling and Time Handling:
- The
rpid
requires a unique random number ID: https://github.com/uuidjs/uuid.
- The
ctime
requires generating a fixed format based on the current time - day.js.
Clear Content and Refocus:
- Clear the content - Set the state controlling the input box's
value
to an empty string.
- 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:
- Parent Component Passing Data: Bind attributes on the child component's tag.
- Child Component Receiving Data: The child component receives the data through the
props
parameter.
1.
props
can pass any type of data:
◦ Numbers
◦ Strings
◦ Booleans
◦ Arrays
◦ Objects
◦ Functions
◦ JSXprops
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
.
Child to Parent Communication:
- Core Idea: The child component calls a function from the parent component and passes arguments to it.
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.
- Component A - APP:
2. APP-B
State Lifting: Elevate the state to the common parent component.
Using Context Mechanism for Cross-Level Component Communication:
- Use the
createContext
method to create a context objectCtx
(you can name it anything).
- In the top-level component (App), provide data using the
Ctx.Provider
component.
- In the lower-level component (B), consume the data using the
useContext
hook.
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.
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 |
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.
Custom Hook function:
Concept: A custom Hook is a function that starts with
By creating a custom Hook, you can encapsulate and reuse logic.
Rules for using React Hooks:
- Hooks can only be called inside components or other custom Hook functions.
- Hooks can only be used at the top level of a component or Hook, and cannot be called inside
if
statements,for
loops, or other functions.
Comment Project
Optimization Requirements:
- Retrieve and render the comment list using an API.
Fetching the Comment List via API:
- 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.
- Use
useEffect
to Fetch Data: - Use the
useEffect
hook to call the API and retrieve data.
Optimization Requirements:
- Encapsulate Data Fetching Logic with a Custom Hook:
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. TheItem
component, 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!