1.子组件 child.js
import react,{Component} from 'react'
export default class Child extends Component{
constructor(props){
super(props)
this.state = { //声明变量
text: '山有木兮木有枝'
}
if(props.onRef){//如果父组件传来该方法 则调用方法将子组件this指针传过去
props.onRef(this)
}
}
dream =(dat)=>{ //定义方法
console.log('父组件调用子组件方法',dat)
}
}
2.父组件 parent.js
import react,{Component} from 'react'
import ChildPage from './child'
export default class Parent extends Component{
fn(){
if(this.ChildPage){
this.ChildPage.dream('哈哈') //调用子组件的dream方法
}
}
render(){
return(
<div className="ParentBig">
<div onClick={ this.fn }>点击</div>
// 把子组件的this指针挂载成父组件的一个变量
<ChildPage onRef={c=>this.ChildPage=c}></ChildPage>
</div>
)
}
}