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>
)
}
本文通过示例代码介绍了如何在React中使用父组件的状态来控制子组件的显示与隐藏。在`parent.js`中,父组件通过设置状态`showChild`并更新该状态来控制子组件的显示。当`showChild`为真时,子组件`child.js`会被渲染。文章提供了两种子组件的实现方式,一种使用`Component`,另一种使用函数组件和`useState` Hook。
1万+

被折叠的 条评论
为什么被折叠?



