React 样式方案与状态方案初探
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 中常见的样式方案和状态管理方案,开发者可以根据项目规模、团队偏好和具体需求选择合适的方案组合。