美文网首页前端之路
react中父组件调用子组件方法(实战版)

react中父组件调用子组件方法(实战版)

作者: 星星藏进黑夜 | 来源:发表于2019-03-29 00:09 被阅读0次

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>
    )
  }
}

相关文章

网友评论

    本文标题:react中父组件调用子组件方法(实战版)

    本文链接:https://www.haomeiwen.com/subject/koyhbqtx.html