react.js如何编写
编写 React.js 的基本步骤
安装 Node.js 和 npm
确保系统中已安装 Node.js 和 npm(Node.js 自带 npm)。可以通过以下命令检查版本:
node -v
npm -v
创建 React 项目
使用 create-react-app 工具快速生成项目结构:
npx create-react-app my-app
cd my-app
npm start
组件开发
函数组件
函数组件是 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
函数组件中通过 Hook 管理状态:
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}
类组件中的状态
类组件通过 this.state 和 this.setState 管理状态:
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
render() {
return (
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Clicked {this.state.count} times
</button>
);
}
}
事件处理
绑定事件
React 事件使用驼峰命名法:
function handleClick() {
console.log('Button clicked');
}
<button onClick={handleClick}>Click me</button>
传递参数
通过箭头函数或 bind 传递参数:
<button onClick={(e) => handleClick(id, e)}>Delete</button>
生命周期方法
类组件的生命周期
常用生命周期方法包括 componentDidMount 和 componentWillUnmount:
class Timer extends React.Component {
componentDidMount() {
this.timerID = setInterval(() => this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({ time: new Date() });
}
}
Hook 替代方案
函数组件中使用 useEffect 替代生命周期:
import { useEffect } from 'react';
function Timer() {
useEffect(() => {
const timerID = setInterval(() => tick(), 1000);
return () => clearInterval(timerID);
}, []);
}
列表渲染
使用 map 渲染列表
通过 map 方法生成元素数组:
const numbers = [1, 2, 3];
const listItems = numbers.map((number) =>
<li key={number}>{number}</li>
);
key 的重要性key 帮助 React 识别列表项的变化:
const todoItems = todos.map((todo) =>
<li key={todo.id}>{todo.text}</li>
);
表单处理
受控组件
表单元素的值由 React 状态控制:
function NameForm() {
const [value, setValue] = useState('');
const handleChange = (event) => setValue(event.target.value);
return <input type="text" value={value} onChange={handleChange} />;
}
表单提交
阻止默认提交行为并处理数据:
function handleSubmit(event) {
event.preventDefault();
console.log('Submitted value:', inputValue);
}
<form onSubmit={handleSubmit}>...</form>
样式处理
内联样式
通过 JavaScript 对象定义样式:
const divStyle = { color: 'blue', fontSize: '20px' };
<div style={divStyle}>Styled text</div>
CSS 模块
使用 CSS 模块实现作用域样式:
import styles from './Button.module.css';
<button className={styles.error}>Error Button</button>
路由配置
安装 React Router
使用 react-router-dom 实现路由:
npm install react-router-dom
基本路由配置
定义路由和导航链接:
import { BrowserRouter, Route, Link } from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<Link to="/">Home</Link>
<Route exact path="/" component={Home} />
</BrowserRouter>
);
}
数据获取
使用 fetch API
从服务器获取数据:
useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data));
}, []);
异步函数
使用 async/await 处理异步请求:
async function fetchData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
setData(data);
}
状态提升
共享状态
将子组件的状态提升到父组件:
function Parent() {
const [value, setValue] = useState('');
return <Child value={value} onChange={setValue} />;
}
function Child({ value, onChange }) {
return <input value={value} onChange={(e) => onChange(e.target.value)} />;
}
上下文 API
创建上下文
通过 createContext 共享全局数据:
const ThemeContext = React.createContext('light');
function App() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
使用上下文
通过 useContext Hook 访问上下文:
function Toolbar() {
const theme = useContext(ThemeContext);
return <div className={theme}>Theme</div>;
}






