React 组件基础学习
学习 React 组件 是掌握 React 开发的核心,因为 组件 是构建 React 应用的 基本单位。掌握如何 创建、使用、传递数据 和 管理状态 是 React 开发 的基础。
1 组件概述
组件 是 React 中 封装 UI 和 行为 的 独立、可复用 的 单元。每个 React 应用 都由 多个组件 组成,可以通过 组件嵌套 来构建 复杂的 界面。
React 支持 两种类型 的组件:
- 函数组件(Function Components);
- 类组件(Class Components)。
2 函数组件(Function Components)
函数组件 是最常用的 组件形式,是一个 返回 JSX 的 普通 JavaScript 函数。
函数组件 没有 内部状态 和 生命周期方法,但可以通过 Hooks(如 useState 和 useEffect)来 增强其功能。
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
// 使用组件
<Greeting name="Alice" />
3 类组件(Class Components)
类组件 是 React 中的一种组件形式,使用 ES6 class 定义。类组件可以有 state(状态)和 生命周期方法,这使它们适用于更复杂的场景。
在 React 16.8 之前,类组件 是必须使用的方式,但现在 函数组件 和 Hook 的出现使得 函数组件 变得 更加流行。
class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
// 使用组件
<Greeting name="Bob" />
4 Props(属性)
Props 是 React 中用于 传递数据 给 组件 的机制。父组件 通过添加 props(属性) 向 子组件 传递数据。props 是 只读的,子组件 不能 直接修改它们,只能读取。
props 可以传递 任何类型 的数据,包括 字符串、数字、数组、对象、函数等。
function Welcome(props) {
return <h1>Welcome, {props.name}!</h1>;
}
// 父组件
<Welcome name="Alice" />
PropTypes 数据类型校验
PropTypes 用于 校验 传入 props 的 数据类型。
import PropTypes from 'prop-types';
function Welcome(props) {
return <h1>Welcome, {props.name}!</h1>;
}
Welcome.propTypes = {
name: PropTypes.string.isRequired,
};
5 State(状态)
State 是 React 中的一个重要概念,它表示 组件内部 的 可变数据。state 用于存储 动态变化 的数据,当 state 发生变化时,组件会 自动重新渲染。
- 在 类组件 中,
state存储在this.state中,并通过this.setState()更新; - 在 函数组件 中,使用
useState钩子来管理组件的状态。
// 类组件 示例
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
increment = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
// 函数组件 示例
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
6 事件处理
React 处理事件的方式 类似于传统 JavaScript,但有一些不同之处:
- React 使用 合成事件系统(
SyntheticEvent),使得事件处理 在不同浏览器之间 更加一致; - 事件处理器 的 函数 需要传递给
onClick、onChange等 事件属性; - 事件处理函数 通常在 函数组件内 定义 并 传递,而在 类组件中 需要 绑定
this。
// 函数组件内定义、传递
function Button() {
const handleClick = () => {
alert('Button clicked!');
};
return <button onClick={handleClick}>Click Me</button>;
}
// 类组件中绑定 this
class Button extends React.Component {
handleClick() {
alert('Button clicked!');
}
render() {
return <button onClick={this.handleClick}>Click Me</button>;
}
}
7 条件渲染
在 React 中,可以通过 JavaScript 条件语句 或 三元运算符 来控制 组件的 渲染。
// 条件语句
function Welcome(props) {
if (props.isLoggedIn) {
return <h1>Welcome back!</h1>;
} else {
return <h1>Please sign up.</h1>;
}
}
// 三目运算符
function Welcome(props) {
return (
<h1>
{props.isLoggedIn ? 'Welcome back!' : 'Please sign up.'}
</h1>
);
}
8 列表渲染
React 允许通过 数组的 map() 方法 动态渲染 列表。每个元素 必须有一个 唯一的 key,React 使用 key 来 优化渲染。
function ItemList(props) {
const items = props.items.map((item) =>
<li key={item.id}>{item.name}</li>
);
return <ul>{items}</ul>;
}
const items = [
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' },
{ id: 3, name: 'Cherry' },
];
<ItemList items={items} />
9 组件的生命周期
在 类组件中,生命周期方法 帮助开发者 在组件的 不同阶段 执行任务。常用的 生命周期方法:
componentDidMount():组件 挂载后 调用;componentDidUpdate():组件 更新后 调用;componentWillUnmount():组件 卸载前 调用。
// 类组件中,组件常用生命周期方法
class Timer extends React.Component {
componentDidMount() {
console.log('Timer component mounted');
}
componentWillUnmount() {
console.log('Timer component will unmount');
}
render() {
return <div>Timer</div>;
}
}
10 React Hooks
在 函数组件中,React 引入了 Hooks 以管理 状态 和 副作用。
- useState 用于 管理状态;
- useEffect 用于 处理副作用(如 数据请求、订阅等)。
// 函数组件中,引入 Hooks 管理状态和副作用
import React, { useState, useEffect } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds(prevSeconds => prevSeconds + 1);
}, 1000);
return () => clearInterval(interval);
}, []);
return <div>Elapsed Time: {seconds} seconds</div>;
}
随着对上述概念的理解,可以 逐步掌握 React 的 核心技巧,并开始使用 React Hooks 和 更复杂的 状态管理方法(如 Redux 或 Context)。