子组件中的代码
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生命周期内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论