1.子組件 child.js
import react,{Component} from 'react'
export default class Child extends Component{
constructor(props){
super(props)
this.state = { //聲明變量
text: '山有木兮木有枝'
}
if(props.onRef){//如果父組件傳來該方法 則調(diào)用方法將子組件this指針傳過去
props.onRef(this)
}
}
dream =(dat)=>{ //定義方法
console.log('父組件調(diào)用子組件方法',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('哈哈') //調(diào)用子組件的dream方法
}
}
render(){
return(
<div className="ParentBig">
<div onClick={ this.fn }>點(diǎn)擊</div>
// 把子組件的this指針掛載成父組件的一個(gè)變量
<ChildPage onRef={c=>this.ChildPage=c}></ChildPage>
</div>
)
}
}