app.js
import React, { Component } from 'react'
import Parent from './components/Parent'
export default class App extends Component {
render() {
return (
<>
<Parent></Parent>
</>
)
}
}
parent.js
import React, { Component } from 'react'
import Child from './Child'
export default class parent extends Component {
state={
showChild:true
}
f2=()=>{
this.setState({
showChild:!this.state.showChild
})
}
render() {
return (
<div style={{backgroundColor:'#dfd'}}>
<h2>父组件</h2>
<button onClick={this.f2}>显示/隐藏</button>
{this.state.showChild && <Child></Child>}
</div>
)
}
}
方法一 child.js
import React, { Component } from 'react'
export default class child extends Component {
state={
count:0
}
f1=()=>{
this.setState({
count:this.state.count+1
})
}
constructor(){
super()
console.log('组件创建')
}
componentDidCatch(){
console.log('组件挂载')
}
render() {
console.log('组件渲染')
return (
<div style={{backgroundColor:'#aaf',margin:'10px',padding:"10px"}}>
<h3>这里是子组件</h3>
<button onClick={this.f1}>点击计数器:{this.state.count}</button>
</div>
)
}
}
方法二 child.js
import React, { useState } from 'react'
export default function Child() {
let [count,f2]=useState(5)
return (
<div>
<h3>子组件</h3>
<button onClick={()=>f2(count+1)}>点击计数器:{count}</button>
</div>
)
}