Yuan的博客
EN

React 基础

项目结构

  • main.jsx 将整个 React 应用注入到 HTML index.html 文件中,并在 <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 脚本

认识 React 组件

function App () {
  return (
    <div>
      <h1>Hello React</h1>
</div> );
}
export default App;

React JSX - JavaScript XML

const title = 'React';
function App () {
  return (
<div>
      <h1>Hello {title}</h1>
</div> );
}
export default App;

React 中的列表 - map()

  • 列表中的每个 React 元素都应该分配一个 key。key 是一个 HTML 属性,应该是一个稳定的标识符。
<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>

认识另一个 React 组件

  • 问题:如何决定何时提取组件? – 答案:当你在代码中发现重复的 UI 模式或功能时提取组件。

React DOM

  • ReactDOM 是 React 中用于将 React 组件渲染到浏览器 DOM 的包

React 组件声明

  • // 函数声明 function App () { ... } // 箭头函数表达式 const App = () => { ... }
  1. 之前
//with block body
const addOne = (count) => {
  //perform any task in between
  return count + 1
}
  1. 之后
//with concise body as one line
const addOne = (count) => count + 1

JSX 中的处理函数

  • 用于输入字段的 change 事件。在 React 中,这个函数被称为(事件)处理器。该函数可以传递给 HTML input 字段的 onChange 属性(JSX 命名属性)
// 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} />

React Props

  • Props(properties 的缩写)是一种从父组件向子组件传递数据的机制。
  • 将它们作为属性包含,如 <MyComponent prop1={value1} prop2={value2} />。向组件传递 props
  • props 是不可变的。它们应该被视为只读

React State

  • React state 引入了可变的数据结构
  • 通过使用 useState,我们告诉 React 我们想要一个随时间变化的有状态值。在 stateful 状态的变量会随着值的改变而进行实时的 render。
  • const [value,setValue] = useState (’')
  • useState 是一个 React hook,允许函数组件管理和更新 state。
  • State 变化或 prop 更新可以触发 React 的重新渲染。

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 ( ... );
};

React 中的状态提升

  • 状态提升是指将 state 从子组件移动到其父组件的做法。
  • 在更高层级共享和管理 state,使多个子组件可以访问。

React 受控组件

  • value prop 设置输入的当前值,使其成为受控组件。

Props 处理(高级)

  • React props 只是一个 JavaScript 对象
  • Props 解构:
    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> );
  • 展开和剩余运算符:
    1. 剩余运算符用于收集多个元素并将它们浓缩为单个数组或对象。不是展开项目,而是将它们聚集在一起
    2. 作为复制或扩展数组和对象中项目的方式。

React 副作用

  • 如果在 useEffect 中省略第二个参数,它会在每次渲染后运行 effect,导致潜在的性能问题

React 自定义 Hooks(高级)

  • 结合 useState 和 useEffect 来创建一种可靠的方式来管理 React 中的持久状态。

React Fragments

  • Fragment 是一种在不引入额外 DOM 元素的情况下将多个 React 元素分组的方式。
  • 使用 <React.Fragment> 或其简写语法 <>...</> 包装元素。
  • Fragments 本身不能有属性。属性应该应用于 Fragment 内的元素。

可复用的 React 组件

  • 通过使用 props 实现可自定义行为,使组件更通用,并确保它们不与特定功能紧密耦合。

React 组件组合

  • React 中的 “Children” 是指放置在组件开始和结束标签之间的内容。

命令式 React

  • 与 useState 不同,useRef 在其值更改时不会触发重新渲染。它通常用于不影响渲染的可变值。
  • 使用 myRef.current 访问使用 useRef 创建的 ref 的当前值。
    inputRef.current.focus()
    

JSX 中的内联处理器

  • 避免在 JSX 中使用复杂逻辑
  • React 中的内联函数通常用作直接在 JSX 中定义的函数。
import React , {useState} from 'react';