本教程將帶你從零開始構建你的第一個 React 應用。我們將創建一個簡單的計數器應用,涵蓋 React 的基本概念和開發流程。
準備工作
在開始之前,請確保你的開發環境滿足以下要求:
-
Node.js (建議使用最新的 LTS 版本)
-
npm 或 yarn (Node.js 安裝時會自帶 npm)
-
代碼編輯器 (如 VS Code)
第一步:創建 React 應用
React 官方推薦使用?create-react-app
?工具來快速搭建項目:
npx create-react-app my-first-react-app
cd my-first-react-app
npm start
執行這些命令后,你的默認瀏覽器應該會自動打開?http://localhost:3000
?并顯示 React 的歡迎頁面。
第二步:理解項目結構
讓我們看一下?create-react-app
?生成的主要文件和目錄:
my-first-react-app/
├── node_modules/ # 所有依賴項
├── public/ # 靜態文件
│ ├── index.html # 主HTML文件
│ └── ...
├── src/ # React 源代碼
│ ├── App.js # 主React組件
│ ├── index.js # 應用入口點
│ └── ...
├── package.json # 項目配置和依賴
└── ...
第三步:創建第一個組件
讓我們修改?src/App.js
?來創建我們的計數器組件:
import React, { useState } from 'react';function App() {// 使用 useState Hook 來管理狀態const [count, setCount] = useState(0);// 增加計數const increment = () => {setCount(count + 1);};// 減少計數const decrement = () => {setCount(count - 1);};// 重置計數const reset = () => {setCount(0);};return (<div style={{ textAlign: 'center', marginTop: '50px' }}><h1>我的第一個 React 應用</h1><h2>計數器: {count}</h2><button onClick={increment} style={{ margin: '5px' }}>增加</button><button onClick={decrement} style={{ margin: '5px' }}>減少</button><button onClick={reset} style={{ margin: '5px' }}>重置</button></div>);
}export default App;
第四步:理解代碼
讓我們分解一下這個簡單的組件:
-
導入 React:
import React, { useState } from 'react';
?- 導入 React 和 useState Hook -
函數組件:我們使用函數式組件而不是類組件,這是 React 的現代寫法
-
useState Hook:
const [count, setCount] = useState(0);
?創建了一個狀態變量?count
?和更新它的函數?setCount
,初始值為 0 -
事件處理:我們定義了三個函數來處理按鈕點擊事件,分別用于增加、減少和重置計數器
-
JSX:返回的 JSX 描述了 UI 的結構和外觀
第五步:運行應用
確保你的開發服務器正在運行(如果沒有,使用?npm start
?啟動它)。你應該能在瀏覽器中看到:
-
一個標題 "我的第一個 React 應用"
-
顯示當前計數的文本
-
三個按鈕:增加、減少和重置
嘗試點擊這些按鈕,觀察計數器的變化。
第六步:添加樣式
讓我們為計數器添加一些基本樣式。在?src/App.js
?中,我們可以添加 CSS-in-JS 樣式:
// 在 return 語句前定義樣式對象
const styles = {container: {textAlign: 'center',marginTop: '50px',fontFamily: 'Arial, sans-serif'},counter: {fontSize: '48px',margin: '20px 0',color: '#333'},button: {padding: '10px 20px',fontSize: '16px',margin: '5px',cursor: 'pointer',backgroundColor: '#61dafb',border: 'none',borderRadius: '5px',color: 'white'},buttonHover: {backgroundColor: '#4fa8d3'}
};// 然后修改 JSX 部分
return (<div style={styles.container}><h1>我的第一個 React 應用</h1><h2 style={styles.counter}>計數器: {count}</h2><button onClick={increment} style={styles.button}onMouseOver={(e) => e.target.style.backgroundColor = styles.buttonHover.backgroundColor}onMouseOut={(e) => e.target.style.backgroundColor = styles.button.backgroundColor}>增加</button>{/* 其他按鈕類似 */}</div>
);
第七步:組件拆分
隨著應用增長,最好將組件拆分為更小的可重用部分。讓我們創建一個單獨的?Counter
?組件:
-
創建?
src/components/Counter.js
:import React, { useState } from 'react';function Counter() {const [count, setCount] = useState(0);const increment = () => setCount(count + 1);const decrement = () => setCount(count - 1);const reset = () => setCount(0);return (<div style={{ textAlign: 'center', margin: '20px' }}><h2>計數器: {count}</h2><button onClick={increment}>增加</button><button onClick={decrement}>減少</button><button onClick={reset}>重置</button></div>); }export default Counter;
-
修改?
src/App.js
:import React from 'react'; import Counter from './components/Counter';function App() {return (<div style={{ textAlign: 'center', marginTop: '50px' }}><h1>我的第一個 React 應用</h1><Counter /></div>); }export default App;
第八步:添加多個計數器
現在我們可以輕松地添加多個計數器實例:
function App() {return (<div style={{ textAlign: 'center', marginTop: '50px' }}><h1>我的第一個 React 應用</h1><Counter /><Counter /><Counter /></div>);
}
每個計數器都有自己獨立的狀態!
第九步:測試與部署
添加單元測試
React 應用通常使用 Jest 和 React Testing Library 進行測試。CRA 已經配置好了這些工具。
創建?src/components/Counter.test.js
:
import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import Counter from './Counter';test('計數器初始值正確', () => {const { getByText } = render(<Counter initialValue={5} />);expect(getByText('當前值: 5')).toBeInTheDocument();
});test('增加按鈕工作正常', () => {const { getByText } = render(<Counter />);fireEvent.click(getByText('+'));expect(getByText('當前值: 1')).toBeInTheDocument();
});
運行測試:
npm test
構建生產版本
準備部署時,運行:
npm run build
這會:
-
優化代碼(壓縮、tree-shaking 等)
-
生成靜態文件到?
build
?目錄 -
準備好部署到任何靜態文件服務器
部署選項
有多種方式可以部署 React 應用:
-
Vercel:最簡單的部署平臺之一
npm install -g vercel vercel
-
Netlify:拖放?
build
?文件夾到 Netlify -
GitHub Pages:
-
安裝?
gh-pages
:npm install gh-pages --save-dev
-
在?
package.json
?中添加:"homepage": "https://username.github.io/repo-name", "scripts": {"predeploy": "npm run build","deploy": "gh-pages -d build" }
-
運行?
npm run deploy
-
React 生態系統豐富而充滿活力,持續學習和實踐是掌握它的關鍵。記住,最好的學習方式是構建真實項目——嘗試擴展這個計數器應用,或者開始一個全新的項目!?