当前位置: 首页 > 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.dtcms.com/a/291748.html

相关文章:

  • Redis 初识
  • SpringMVC快速入门之核心配置详解
  • 【安卓笔记】用MVC、MVP、MVVM来实现井字棋案例
  • 厌氧菌数据挖掘可行性评估报告
  • 【Spark征服之路-3.7-Spark-SQL核心编程(六)】
  • 解决栅格数据裁剪矢量数据问题两种方法,ArcGIS解决与PYTHON解决
  • Ajax第一天
  • uniapp各大平台导航组件
  • Taro 网络 API 详解与实用案例
  • JavaScript AJAX 实现,演示如何将 Token 添加到 Authorization
  • 异地服务器备份Mysql数据
  • 电子电气架构 --- 从软件质量看组织转型路径
  • 基于Patroni实现PostgreSQL数据库高可用
  • postgresql使用记录 SCRAM authentication requires libpq version 10 or above
  • Nginx防盗链和Keepalived
  • VirtualBox安装提示security安全问题
  • 【coze扣子】第1篇:coze快速入门
  • 消息队列学习
  • 3.4 安全-分布式-数据库-挖掘
  • LNMP平台部署
  • 【uboot/kernel1】启动流程,环境变量,内存,initramfs
  • 【大模型记忆实战Demo】基于SpringAIAlibaba通过内存和Redis两种方式实现多轮记忆对话
  • 本地代理和服务器代理区别
  • 【AI时代速通QT】第五节:Qt Creator如何引入第三方库,以OpenCV为例
  • 深入解析MIPI C-PHY (三)C-PHY 功耗屠龙刀
  • FunASR 说话人识别 Xvector 环境版本配置
  • 一文读懂深度模型优化器,掌握炼丹工具
  • 【数学建模】基础知识
  • FTP考点
  • SparkSQL 聚合函数 COUNT 对 NULL 值的处理