当前位置: 首页 > news >正文

【React 入门系列】React 组件通讯与生命周期详解

🧩 第一章:组件通讯概述

在 React 开发中,组件是封装的、独立的功能单元。为了实现组件间的数据共享与协作,需要通过组件通讯机制

组件通讯的意义:
让多个封闭的组件能够共享数据,实现协作功能。


📥 第二章:组件 Props 基础与进阶

1. Props 的基本使用

组件是封闭的,要接收外部数据应通过 props(属性) 实现。

✅ 使用方式:
  • 传递数据:给组件标签添加属性
  • 接收数据
    • 函数组件:通过参数 props 接收
    • 类组件:通过 this.props 接收
✅ 示例:
<Hello name="jack" age={19} />
// 函数组件
function Hello(props) {return <div>接收到数据:{props.name}</div>;
}
// 类组件
class Hello extends React.Component {render() {return <div>接收到数据:{this.props.age}</div>;}
}

2. Props 的特点

  1. 可传递任意类型数据

    <Helloname="root"age={19}colors={['red', 'blue']}fn={() => console.log('函数')}tag={<h1>标签</h1>}
    />
  2. 只读对象
    props 是只读的,不能直接修改。

  3. 构造函数中使用 props
    如果类组件有构造函数,必须将 props 传入 super(),否则无法在构造函数中访问 props。

    constructor(props) {super(props);
    }

3. 组件通信的三种方式

✅ 1. 父组件 → 子组件

步骤:

  1. 父组件通过 state 传递数据
  2. 子组件通过 props 接收数据
class Parent extends React.Component {state = { lastName: "王" };render() {return <Child name={this.state.lastName} />;}
}
function Child(props) {return <div>子组件接收到数据:{props.name}</div>;
}

✅ 2. 子组件 → 父组件

使用回调函数实现:

  1. 父组件定义回调函数,并传给子组件
  2. 子组件调用回调,传入数据
class Parent extends React.Component {getChildMsg = (msg) => {console.log("接收到子组件数据", msg);};render() {return <Child getMsg={this.getChildMsg} />;}
}
class Child extends React.Component {state = { childMsg: "react" };handleClick = () => {this.props.getMsg(this.state.childMsg);};return <button onClick={this.handleClick}>点击传值</button>;
}

✅ 3. 兄弟组件通信

核心思想:状态提升(Lifting State Up)

  1. 将共享状态提升到公共父组件
  2. 父组件提供状态和更新方法
  3. 子组件通过 props 接收并使用
class App extends React.Component {state = { count: 0 };handleClick = () => {this.setState({ count: this.state.count + 1 });};render() {return (<div><Zi num={this.state.count} /><Zi2 numadd={this.handleClick} /></div>);}
}
function Zi(props) {return <div>count: {props.num}</div>;
}function Zi2(props) {return <button onClick={props.numadd}>Click Me</button>;
}

✅ 4. Context 组件(跨层级通信)

当组件嵌套较深或为“远方亲戚”时,使用 Context 实现通信更高效。

使用步骤:

  1. 创建 Provider 和 Consumer
const { Provider, Consumer } = React.createContext();
  1. 使用 Provider 提供数据
<Provider value="pink"><div className="APP"><Child /></div>
</Provider>
  1. 使用 Consumer 消费数据
<Consumer>{data => <span>数据为:{data}</span>}
</Consumer>

🧠 第三章:Props 深入理解

1. children 属性

表示组件标签的子节点,可以是任意类型:文本、React 元素、组件、甚至是函数。

function Hello(props) {return <div>组件的子节点:{props.children}</div>;
}
<Hello>我是子节点</Hello>

2. Props 校验(PropTypes)

使用 prop-types 包进行类型校验,确保组件接收的数据符合预期。

安装:

npm install prop-types

使用:

import PropTypes from 'prop-types';App.propTypes = {colors: PropTypes.array,fn: PropTypes.func.isRequired,shape: PropTypes.shape({id: PropTypes.number,name: PropTypes.string})
};

3. Props 默认值(defaultProps)

设置默认值,防止 props 未传时出错。

App.defaultProps = {pageSize: 10
};
function App(props) {return <div>默认值:{props.pageSize}</div>;
}

🕒 第四章:组件生命周期详解

组件的生命周期分为三个阶段:创建、更新、卸载,每个阶段都有对应的钩子函数。

1. 创建阶段(Mounting)

执行时机:组件创建时(页面加载时)

执行顺序:

constructor → render() → componentDidMount
  • constructor:初始化 state,绑定 this
  • render:渲染 UI(不能调用 setState
  • componentDidMount:组件挂载后,适合发送网络请求、DOM 操作
constructor(props) {super(props);this.state = { count: 0 };
}
componentDidMount() {console.log('组件已挂载');
}

2. 更新阶段(Updating)

执行时机:组件更新时(如调用 setState()forceUpdate() 或接收到新的 props)

执行顺序:

render() → componentDidUpdate()
  • render:重新渲染 UI
  • componentDidUpdate:组件更新后,适合发送网络请求、DOM 操作
componentDidUpdate(prevProps, prevState) {if (prevState.count !== this.state.count) {console.log('组件已更新');}
}

3. 卸载阶段(Unmounting)

执行时机:组件从页面消失

执行函数:

componentWillUnmount() {// 清理工作,如清除定时器、取消订阅等
}

📚 总结

模块内容
组件通讯Props、回调函数、Context、状态提升
Props传递任意类型数据、只读、children、校验、默认值
生命周期创建、更新、卸载阶段,各阶段钩子函数用途
http://www.lryc.cn/news/596678.html

相关文章:

  • 高可用架构模式——数据集群和数据分区
  • 单细胞转录组学+空间转录组的整合及思路
  • OneCode3.0 UI组件注解详解手册
  • 【vscode】vscode中python虚拟环境的创建
  • 回调地狱及解决方法
  • error C++17 or later compatible compiler is required to use ATen.
  • 【coze扣子】第1篇:coze快速入门
  • 威胁情报:Solana 开源机器人盗币分析
  • 以Java程序员角度理解MCP
  • 学习游戏制作记录(战斗系统简述以及击中效果)7.22
  • [c++11]std::function/bind
  • 基于SpringBoot+Vue的班级管理系统(Echarts图形化分析)
  • 101.对称二叉树
  • ubuntu 20.04 安装 cmake 3.26
  • VS Code 美化插件
  • 3ds Max 云端渲染插件 - 完整 Python 解决方案
  • Mysql-场景篇-2-线上高频访问的Mysql表,如何在线修改表结构影响最小?-1--Mysql8.0版本后的INSTANT DDL方案(推荐)
  • 基于mysql云数据库创建和美化表格,对比分析Power BI和Quick BI的功能优劣
  • 基于eBPF的Kubernetes网络故障自愈系统设计与实现
  • AI一周事件(2025年7月15日-7月21日)
  • 【Spring AI 0基础教程】1、基础篇 环境搭建 - 智能天气预报助手
  • 数据资产——解读数据资产全过程管理手册2025【附全文阅读】
  • 【时时三省】(C语言基础)指向函数的指针
  • 发票识别在费控系统应用剖析
  • Dify-13: 文本生成API端点
  • uniapp打开导航软件并定位到目标位置的实现
  • 从零搭建 OpenCV 项目(新手向)--第一天初识OpenCV与图像基础
  • 京东视觉算法面试30问全景精解
  • Thinkphp8使用Jwt生成与验证Token
  • 最新基于R语言结构方程模型分析与实践技术应用