【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 的特点
可传递任意类型数据
<Helloname="root"age={19}colors={['red', 'blue']}fn={() => console.log('函数')}tag={<h1>标签</h1>} />
只读对象
props 是只读的,不能直接修改。构造函数中使用 props
如果类组件有构造函数,必须将 props 传入super()
,否则无法在构造函数中访问 props。constructor(props) {super(props); }
3. 组件通信的三种方式
✅ 1. 父组件 → 子组件
步骤:
- 父组件通过
state
传递数据 - 子组件通过
props
接收数据
class Parent extends React.Component {state = { lastName: "王" };render() {return <Child name={this.state.lastName} />;}
}
function Child(props) {return <div>子组件接收到数据:{props.name}</div>;
}
✅ 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)
- 将共享状态提升到公共父组件
- 父组件提供状态和更新方法
- 子组件通过 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
实现通信更高效。
使用步骤:
- 创建
Provider
和Consumer
const { Provider, Consumer } = React.createContext();
- 使用
Provider
提供数据
<Provider value="pink"><div className="APP"><Child /></div>
</Provider>
- 使用
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,绑定 thisrender
:渲染 UI(不能调用setState
)componentDidMount
:组件挂载后,适合发送网络请求、DOM 操作
constructor(props) {super(props);this.state = { count: 0 };
}
componentDidMount() {console.log('组件已挂载');
}
2. 更新阶段(Updating)
执行时机:组件更新时(如调用 setState()
、forceUpdate()
或接收到新的 props)
执行顺序:
render() → componentDidUpdate()
render
:重新渲染 UIcomponentDidUpdate
:组件更新后,适合发送网络请求、DOM 操作
componentDidUpdate(prevProps, prevState) {if (prevState.count !== this.state.count) {console.log('组件已更新');}
}
3. 卸载阶段(Unmounting)
执行时机:组件从页面消失
执行函数:
componentWillUnmount() {// 清理工作,如清除定时器、取消订阅等
}
📚 总结
模块 | 内容 |
---|---|
组件通讯 | Props、回调函数、Context、状态提升 |
Props | 传递任意类型数据、只读、children、校验、默认值 |
生命周期 | 创建、更新、卸载阶段,各阶段钩子函数用途 |