父组件中定义一个回调函数,由子组件来调用执行。用this.props.[父组件自定义回调函数名称]()调用
/*
* @Author: Spring
* @LastEditors: Aidam_Bo
* @LastEditTime: 2023-01-01 21:00:32
*/
import React, { Component } from 'react'
//子传父:父中定义一个回调函数,由子组件来调用执行。用this.props.[父组件自定义回调函数名称]()
//子
class Navbar extends Component{
render(){
return <div style={{background:"red"}}>
<button onClick={()=>{
console.log('子通知父,让父的isShow取反',this.props.event);
this.props.event();//调用父组件传过来的回调函数
}}>切换</button>
<span>Siderbar</span>
</div>
}
}
//子
class Siderbar extends Component{
render(){
return <div style={{background:"yellow",width:"200px"}}>
<ol>
<li>7</li>
<li>7</li>
<li>7</li>
<li>7</li>
<li>7</li>
<li>7</li>
<li>7</li>
</ol>
</div>
}
}
//父
export default class App extends Component {
//state只有在父组件App中取得到。子组件中访问不到
state={
isShow:true
}
render() {
return (
<div>
<Navbar event={()=>{
console.log("父组件中的自定义事件event不会自己执行");
this.setState({
isShow:!this.state.isShow
})
}}></Navbar>
{this.state.isShow && <Siderbar></Siderbar>}
</div>
)
}
}