史上最简单易理解的 React 子组件调用父组件方法
我们只要记住 父组件通过 isShow={this.hideSon}来绑定方法。
子组件通过props 来接收这个方法 ,然后通过 onClick={ isShow }来执行父组件的方法。
这下就非常明白了,关键点就在isShow
在父组件中 isShow 用来代替onClick
在子组件中onClick 来点击 isShow。
import React,{Component} from "react"
//子组件
class Son extends Component{
constructor(props){
super(props);
}
render(){
const {isShow} =this.props;
return(
<div onClick={isShow}>
我是子组件
</div>
)
}
}
export default class sonCallfather extends Component{
constructor(props){
super(props);
this.state={
isshow:true
}
}
hideSon =() =>{
this.setState({
isshow:false
});
}
showSon =() =>{
this.setState({
isshow:true
});
}
render(){
const {isshow} =this.state;
return(
<div>
子组件在父组件里面展示
{isshow ? <Son isShow={this.hideSon}/> :
<div onClick={this.showSon}>
我影藏了,点我就出来
</div>}
</div>
)
}
}
网友评论