子传父(React)

收藏

子传父是通过回调函数

import React, { Component } from 'react'
class Navbar extends Component {
  render() {
    return (
      <div style={{background:"red"}}>
        <button onClick={()=>{this.props.event()}}>click</button>
        <span>navbar</span>
      </div>
    )
  }
}
class Sidebar extends Component {
    render() {
      return (
        <div style={{background:"yellow"}}>
          <ul>
            <li>Home</li>
          </ul>
        </div>
      )
    }
  }
export default class App extends Component {
    state={
        show:true
    }
  render() {
    return (
      <div>
        <Navbar event={()=>{
            this.setState({
                show:!this.state.show
            })
        }}/>
        {this.state.show && <Sidebar />}
      </div>
    )
  }
}

父:

  <Navbar event={()=>{
            this.setState({
                show:!this.state.show
            })
   }}/>

子:

   <button onClick={()=>{this.props.event()}}>click</button>


评论(

您还未登录,请先去登录
表情
查看更多

相关作者

  • 获取点赞0
  • 文章阅读量264

相关文章

联系小鹿线

咨询老师

咨询老师

扫码下载APP