react中父组件控制子组件的显示与隐藏

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>

  )

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值