Fundamentals of React
Project Structure
hacker-stories/ –node_modules/ –public/ —-vite.svg –src/ —-assets/ ——react.svg —-App.css —-App.jsx —-index.css —-main.jsx –.eslintrc.cjs –.gitignore –index.html –package-lock.json –package.json –README.md –vite.config.js
- main.jsx injects the entire React application into the HTML index.html file, displaying it inside the
<div id="root">
.
{/* index.html */}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>My React App</title>
</head>
<body>
<div id="root"></div>
{/* This script will load the bundled JavaScript files created by React */}
<script type="module" src="/main.js"></script>
</body>
</html>
//main.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App'; // Importing the main App component
import './index.css'; // Importing global styles
// Find the 'root' div in index.html and attach the app to it
const root = ReactDOM.createRoot (document.getElementById ('root'));
// Render the <App /> component, which contains the main structure of the app
root.render (<App />);
// App.js
import React from 'react'; // Import the React library
import './App.css'; // Import styles specific to App component
// Define the App component
function App () {
return (
<div className="app-container">
<h1>Welcome to My React App!</h1>
<p>This is a simple example of a React component structure.</p>
</div>
);
}
// Export the App component so it can be used in other files
export default App;
npm Scripts
meet the react component
function App () {
return (
<div>
<h1>Hello React</h1>
</div> );
}
export default App;
react JSX-javaScriptXml
const title = 'React';
function App () {
return (
<div>
<h1>Hello {title}</h1>
</div> );
}
export default App;
- jsx 是 javaScript 和 HTML 的结合,语言更接近于 javascript.html 中有些属性的名字会有所改变,而 javascript 中的变量则是用括号来表示。jsx 语言目前在 js 文件中也能够被转译。
Lists in React- map ()
- every React element in a list should have a key assigned to it. The key is an HTML attribute and should be a stable identifier.
<ul>
{list.map (function (item) {
return <li key={item.objectID}>{item.title}</li>;
})} </ul>
<ul>
{list.map (function (item){
return <a href={item.url}>{item.title}</a>
})}
</ul>
meet another react component
- Question: How do you decide when to extract a component? – Answer: Extract a component when you find repeated UI patterns or functionality within your code.
React Component Instantiation
- JavaScript class with declaration and instantiation:在 javascript 中 用 class (里面一般包含 constructor 去 take arguments and assign them to the class,也能包含函数被叫做 methods ,如果想要用 class 生成新的 object,则是需要 const xx = className (参数))
- jsx 中需要用 component 去产生 instance
React DOM
- ReactDOM is a package in React used for rendering React components into the browser DOM
React Component Declaration
- //function declaration
function App () { ... }
//arrow function expressionconst App = () => { ... }
- 箭头函数中,如果函数体中没有额外的操作执行,可以把大括号和 return 语句去掉,直接简化。
- 简化前
//with block body
const addOne = (count) => {
//perform any task in between
return count + 1
}
- 简化后
//with concise body as one line
const addOne = (count) => count + 1
Handler Function in JSX
- for the change event of the input field. In React, this function is called an (event) handler.the function can be passed to the onChange attribute (JSX named attribute) of the HTML input field
// Define the handler function
const handleChange = (event) => {
console.log (event.target.value);
};
//if handleChange is a function
//which does not return a function
//don't do this
<input onChange={handleChange ()} />
// 这个时候调用的是一个值,你在输入文字也不能调用函数实时更新,
//do this instead
<input onChange={handleChange} />
// 这里面 handleChange 是 handler function. input 里面则是 event handler。
React Props
- Props (short for properties) are a mechanism for passing data from a parent component to a child component.
- Include them as attributes, like
<MyComponent prop1={value1} prop2={value2} />
. Pass props to a component - props are immutable. They should be treated as read-only
React State
- React state introduces a mutable data structure
- By using useState, we are telling React that we want to have a stateful value which changes over time. 在 stateful 状态的变量会随着值的改变而进行实时的 render。
- const [value,setValue] = useState (’’) value 最新的值 setValue 是更新值的函数 ’’ 是初始值
- useState is a React hook that allows function components to manage and update state.
- State changes or prop updates can trigger a re-render in React.
Callback Handlers in JSX
const App = () => {
const stories = [ ... ];
// A
const handleSearch = (event) => {
// D
console.log (event.target.value);
};
return (
<div>
<h1>My Hacker Stories</h1>
{/* // B */}
<Search onSearch={handleSearch} />
<hr />
<List list={stories} />
</div>
); };
const Search = (props) => {
const [searchTerm, setSearchTerm] = React.useState ('');
const handleChange = (event) => {
setSearchTerm (event.target.value);
// C
props.onSearch (event);
};
return ( ... );
};
// 主要是 onSearch 把最新的值调用回了父函数
Lifting State in React
- Lifting state refers to the practice of moving the state from a child component to its parent component.
- To share and manage state at a higher level, making it accessible to multiple child components.
React Controlled Components
- The value prop sets the current value of the input, making it a controlled component.
Props Handling (Advanced)
- React props are just a JavaScript object
- Props Destructuring:
const { search, onSearch } = props const Search = ({ search, onSearch }) => { //component logic }
- Nested Destructuring:
const Item = ({
item: {
title,
url,
author,
num_comments,
points,
},
}) => ( <li>
<span>
<a href={url}>{title}</a>
</span>
<span>{author}</span>
<span>{num_comments}</span>
<span>{points}</span>
</li> );
- Spread and Rest Operators:
- The rest operator is used to collect multiple elements and condense them into a single array or object.instead of spreading items out, it gathers them together
- it as a way to copy or expand items in arrays and objects.
React Side-Effects
- you omit the second argument in useEffect,It runs the effect after every render, leading to potential performance issues
React Custom Hooks (Advanced)
- Combines useState and useEffect to create a reliable way to manage persistent state in React.
React Fragments
- A Fragment is a way to group multiple React elements without introducing an additional DOM element.
- Wrap the elements with
<React.Fragment>
or its shorthand syntax<>...</>
. - Fragments themselves cannot have attributes. Attributes should be applied to the elements within the Fragment.
Reusable React Component
-Make components more generic by using props for customizable behavior and ensuring they are not tightly coupled to specific functionalities.
React Component Composition
- “Children” in React refers to the content placed between the opening and closing tags of a component.
Imperative React
- Unlike useState, useRef doesn’t trigger a re-render when its value changes. It’s often used for mutable values that don’t affect the rendering.
- Use myRef.current to access the current value of a ref created with useRef.
inputRef.current.focus()
Inline Handler in JSX
- avoid using complex logic in JSX
- An inline function in React is often used as a function defined directly within the JSX.
import React , {useState} from 'react';