ai-coding-demo

什么是 React?

📖 概述

React 是 Facebook(现 Meta)于 2013 年开源的 JavaScript 库,用于构建用户界面,特别是单页应用。它专注于视图层,采用组件化开发模式,使用虚拟 DOM 提高渲染性能。React 已成为前端开发的主流框架之一。

🌟 核心特性

1. 组件化开发

2. JSX 语法

3. 虚拟 DOM

4. 单向数据流

5. Hooks 特性

🏗️ 项目结构

my-react-app/
├── public/
│   ├── index.html
│   └── favicon.ico
├── src/
│   ├── components/     # 组件目录
│   ├── pages/         # 页面组件
│   ├── hooks/         # 自定义 Hooks
│   ├── App.js         # 根组件
│   ├── index.js       # 入口文件
│   └── index.css      # 全局样式
├── package.json
└── README.md

💻 基本语法

1. 函数组件

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>
}

2. 类组件

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>
  }
}

3. 使用 Hooks

import { useState } from 'react'

function Counter() {
  const [count, setCount] = useState(0)

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  )
}

4. 条件渲染

function Greeting({ isLoggedIn }) {
  if (isLoggedIn) {
    return <h1>欢迎回来!</h1>
  }
  return <h1>请登录</h1>
}

5. 列表渲染

function List({ items }) {
  return (
    <ul>
      {items.map(item => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  )
}

🎯 React Hooks

useState

const [state, setState] = useState(initialValue)

useEffect

useEffect(() => {
  // 副作用逻辑
  return () => {
    // 清理逻辑
  }
}, [dependencies])

useContext

const value = useContext(MyContext)

自定义 Hook

function useCounter(initialValue = 0) {
  const [count, setCount] = useState(initialValue)
  const increment = () => setCount(count + 1)
  return { count, increment }
}

📦 核心生态

🚀 开发流程

1. 创建项目

# 使用 Create React App
npx create-react-app my-app
cd my-app
npm start

# 使用 Vite(推荐)
npm create vite@latest my-app -- --template react
cd my-app
npm install
npm run dev

2. 构建项目

npm run build

3. 项目结构示例

App.js

import { useState } from 'react'
import './App.css'

function App() {
  const [count, setCount] = useState(0)

  return (
    <div className="App">
      <h1>React Demo</h1>
      <p>Counter: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        Increment
      </button>
    </div>
  )
}

export default App

✅ 优缺点

优点

缺点

🎯 适用场景

📚 学习资源

🔗 相关链接