子传父是通过回调函数
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
评论()