React中如何写
在React中编写代码需要遵循其组件化、声明式编程等核心理念。以下是关键实践方法:
组件化开发
React应用由独立组件构成,每个组件管理自身的状态和UI。函数组件是推荐方式:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
类组件适用于需要生命周期方法的场景:
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
状态管理
使用useState钩子管理组件内部状态:
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}
复杂状态逻辑可使用useReducer:
function reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1};
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, {count: 0});
return (
<button onClick={() => dispatch({type: 'increment'})}>
Count: {state.count}
</button>
);
}
生命周期管理
函数组件使用useEffect处理副作用:
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]); // 仅在count变化时更新
事件处理
采用驼峰命名法绑定事件:
<button onClick={handleClick}>
Click me
</button>
阻止默认行为需显式调用preventDefault:
function handleSubmit(e) {
e.preventDefault();
console.log('Form submitted');
}
条件渲染
使用逻辑与运算符进行条件渲染:
{isLoggedIn && <UserGreeting />}
三目运算符处理两种状态:
{isLoggedIn ? <UserGreeting /> : <GuestGreeting />}
列表渲染
使用map()渲染列表时需指定key:
const numbers = [1, 2, 3];
const listItems = numbers.map((number) =>
<li key={number.toString()}>
{number}
</li>
);
表单处理
受控组件通过状态管理表单数据:
function NameForm() {
const [value, setValue] = useState('');
const handleChange = (event) => {
setValue(event.target.value);
};
return (
<input type="text" value={value} onChange={handleChange} />
);
}
上下文共享
使用Context API跨组件共享数据:
const ThemeContext = React.createContext('light');
function App() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
性能优化
使用React.memo避免不必要的重渲染:
const MemoizedComponent = React.memo(function MyComponent(props) {
/* 使用props渲染 */
});
复杂计算使用useMemo缓存:

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);






