React 本身只提供了基礎 UI 層開發范式,其他特性的支持需要借助相關社區方案實現。本文將介紹 React 應用體系中樣式方案與狀態方案的主流選擇,幫助開發者根據項目需求做出合適的選擇。
1.?React 樣式方案
1.1. 內聯樣式 (Inline Styles)
通過 style 屬性直接在組件中定義樣式。
const divStyle = {color: 'blue',backgroundColor: 'lightgray'
};function StyledComponent() {return <div style={divStyle}>Hello, world!</div>;
}
1.2. CSS 模塊 (CSS Modules)
CSS 模塊允許為 CSS 類名添加局部作用域,避免樣式沖突。文件名通常以 .module.css 結尾。
/* styles.module.css */
.container {color: red;
}
頁面中使用:
import styles from './styles.module.css';function StyledComponent() {return <div className={styles.container}>Hello, world!</div>;
}
1.3. Styled Components
使用 styled-components 庫可以在 JavaScript 中編寫實際的 CSS,提供了組件級別的樣式管理。
安裝:
npm install styled-components
示例:
import styled from 'styled-components';const Container = styled.div`color: blue;background-color: lightgray;
`;function StyledComponent() {return <Container>Hello, world!</Container>;
}
1.4. Emotion
Emotion 是一個強大的 CSS-in-JS 庫,提供了靈活的樣式管理方案。
安裝:
npm install @emotion/react @emotion/styled
示例:
/** @jsxImportSource @emotion/react */
import { css } from '@emotion/react';const style = css`color: blue;background-color: lightgray;
`;function StyledComponent() {return <div css={style}>Hello, world!</div>;
}
1.5. Tailwind CSS
Tailwind CSS 是一個實用工具優先的 CSS 框架,可以在 React 項目中使用。
安裝:
npm install tailwindcss
npx tailwindcss init
示例:
function StyledComponent() {return <div className="text-blue-500 bg-gray-200">Hello, world!</div>;
}
2.?React 狀態方案
2.1. useState 和 useReducer
useState 和 useReducer 是 React 內置的 Hook,用于管理組件級別的狀態。
useState 示例:
import React, { 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>);
}
useReducer 示例:
import React, { useReducer } from 'react';const initialState = { count: 0 };function reducer(state, action) {switch (action.type) {case 'increment':return { count: state.count + 1 };case 'decrement':return { count: state.count - 1 };default:throw new Error();}
}function Counter() {const [state, dispatch] = useReducer(reducer, initialState);return (<div><p>Count: {state.count}</p><button onClick={() => dispatch({ type: 'increment' })}>+</button><button onClick={() => dispatch({ type: 'decrement' })}>-</button></div>);
}
2.2.?Context API
React 的 Context API 允許在組件樹中傳遞數據,而無需手動逐層傳遞 props。
import React, { createContext, useContext, useState } from 'react';const ThemeContext = createContext();function ThemeProvider({ children }) {const [theme, setTheme] = useState('light');return (<ThemeContext.Provider value={{ theme, setTheme }}>{children}</ThemeContext.Provider>);
}function ThemeComponent() {const { theme, setTheme } = useContext(ThemeContext);return (<div><p>Current theme: {theme}</p><button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>Toggle Theme</button></div>);
}function App() {return (<ThemeProvider><ThemeComponent /></ThemeProvider>);
}export default App;
2.3. Redux
Redux 是一個流行的狀態管理庫,適用于復雜的應用程序。Redux 使用單一的全局狀態樹來管理應用的狀態。
安裝:
npm install redux react-redux
配置:
import { createStore } from 'redux';
import { Provider, useDispatch, useSelector } from 'react-redux';const initialState = { count: 0 };function reducer(state = initialState, action) {switch (action.type) {case 'increment':return { count: state.count + 1 };case 'decrement':return { count: state.count - 1 };default:return state;}
}const store = createStore(reducer);function Counter() {const count = useSelector(state => state.count);const dispatch = useDispatch();return (<div><p>Count: {count}</p><button onClick={() => dispatch({ type: 'increment' })}>+</button><button onClick={() => dispatch({ type: 'decrement' })}>-</button></div>);
}function App() {return (<Provider store={store}><Counter /></Provider>);
}export default App;
2.4. MobX
MobX 是另一個流行的狀態管理庫,注重使狀態管理更加直觀和簡單。
安裝:
npm install mobx mobx-react-lite
示例:
import React from 'react';
import { makeAutoObservable } from 'mobx';
import { observer } from 'mobx-react-lite';class CounterStore {count = 0;constructor() {makeAutoObservable(this);}increment() {this.count++;}decrement() {this.count--;}
}const counterStore = new CounterStore();const Counter = observer(() => {return (<div><p>Count: {counterStore.count}</p><button onClick={() => counterStore.increment()}>+</button><button onClick={() => counterStore.decrement()}>-</button></div>);
});function App() {return (<div><Counter /></div>);
}export default App;
以上介紹了 React 中常見的樣式方案和狀態管理方案,開發者可以根據項目規模、團隊偏好和具體需求選擇合適的方案組合。