如何用react
使用 React 的基本步骤
安装 React
通过 create-react-app 快速搭建项目环境:
npx create-react-app my-app
cd my-app
npm start
或者使用 Vite 等现代构建工具:
npm create vite@latest my-react-app --template react
cd my-react-app
npm install
npm run dev
组件开发
React 的核心是组件化开发,分为函数组件和类组件。
函数组件示例:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
类组件示例:
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
状态管理
函数组件使用 useState Hook 管理状态:

import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}
类组件通过 this.state 和 setState 管理状态:
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
handleClick = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<button onClick={this.handleClick}>
Clicked {this.state.count} times
</button>
);
}
}
生命周期与副作用
函数组件使用 useEffect 处理副作用:
import { useEffect } from 'react';
function DataFetcher() {
useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data));
}, []); // 空依赖数组表示仅在组件挂载时执行
}
类组件的生命周期方法:

class DataFetcher extends React.Component {
componentDidMount() {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data));
}
render() {
return <div>Fetching data...</div>;
}
}
事件处理
React 事件使用驼峰命名(如 onClick),并阻止默认行为需显式调用 e.preventDefault():
function Form() {
const handleSubmit = (e) => {
e.preventDefault();
console.log('Form submitted');
};
return <form onSubmit={handleSubmit}>...</form>;
}
条件渲染
通过逻辑运算符或三元表达式实现条件渲染:
function Greeting({ isLoggedIn }) {
return isLoggedIn ? <UserGreeting /> : <GuestGreeting />;
}
列表渲染
使用 map 渲染列表,并为每个项添加唯一 key:
function TodoList({ todos }) {
return (
<ul>
{todos.map(todo => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
);
}
进阶工具
- 状态管理库:Redux、MobX 或 Context API。
- 路由:React Router 实现多页面导航。
- 样式方案:CSS Modules、Styled-components 或 Tailwind CSS。
通过以上方法,可以逐步掌握 React 的核心功能并构建复杂应用。






