子组件中的代码
import React from "react";
class Son extends React.Component {
// 构造函数:初始化状态
constructor(props) {
super(props);
// 使用 props 初始化 state
this.state = {
count: props.initialCount || 0, // 从 props 传入的初始计数
name: props.name || "Son", // 从 props 传入的初始名称
isshow: props.isshow || true, // 从 props 传入的初始是否显示
};
}
componentDidMount() {
console.log("son componentDidMount");
}
// shouldComponentUpdate - 控制是否更新组件
shouldComponentUpdate(nextProps, nextState) {
console.log("son shouldComponentUpdate");
return true; // 默认返回 true,表示每次都更新
}
// componentDidUpdate - 更新后调用
componentDidUpdate(prevProps, prevState) {
console.log("son componentDidUpdate");
}
// componentWillUnmount - 组件卸载前调用
componentWillUnmount() {
console.log("son componentWillUnmount");
}
// 增加计数的方法
increment = () => {
this.setState((prevState) => ({
count: prevState.count + 1,
}));
};
// 减少计数的方法
decrement = () => {
this.setState((prevState) => ({
count: prevState.count - 1,
}));
};
// 渲染方法:显示组件内容
render() {
return (
<div>
{this.state.isshow && (
<div>
<h2>计数器</h2>
<p>当前名字: {this.state.name}</p>
<p>当前计数: {this.state.count}</p>
<button onClick={this.increment}>增加</button>
<button onClick={this.decrement}>减少</button>
</div>
)}
</div>
);
}
}
export default Son;
父组件中代码
import React from "react";
import Son from "./son";
class fa extends React.Component {
constructor(props) {
super(props);
// 使用 props 初始化 state
this.state = {
isshow:true
};
}
componentDidMount() {
console.log("fa componentDidMount");
}
// shouldComponentUpdate - 控制是否更新组件
shouldComponentUpdate(nextProps, nextState) {
console.log("fa shouldComponentUpdate");
return true; // 默认返回 true,表示每次都更新
}
// componentDidUpdate - 更新后调用
componentDidUpdate(prevProps, prevState) {
console.log("fa componentDidUpdate");
}
// componentWillUnmount - 组件卸载前调用
componentWillUnmount() {
console.log("fa componentWillUnmount");
}
render() {
return (
<div>
<h1>父组件</h1>
<button onClick={()=>{
this.setState({
isshow:!this.state.isshow
})
}}>显示/隐藏</button>
{/* 传递 initialCount 到子组件 Counter */}
<Son initialCount={5} name={"liu"} isshow={this.state.isshow}/>
</div>
);
}
}
export default fa;
挂载时候打印出来的是

当子组件中counter进行更新时候执行的生命周期

当子组件卸载时候执行的生命周期

每个阶段的生命周期

到此这篇关于react类标签的生命周期的文章就介绍到这了,更多相关react生命周期内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
来源链接:https://www.jb51.net/javascript/3303337c3.htm
© 版权声明
本站所有资源来自于网络,仅供学习与参考,请勿用于商业用途,否则产生的一切后果将由您(转载者)自己承担!
如有侵犯您的版权,请及时联系3500663466#qq.com(#换@),我们将第一时间删除本站数据。
如有侵犯您的版权,请及时联系3500663466#qq.com(#换@),我们将第一时间删除本站数据。
THE END












暂无评论内容