美文网首页
父组件调用子组件方法

父组件调用子组件方法

作者: INGME | 来源:发表于2020-08-31 18:30 被阅读0次
在父组件中调用子组件的实例:
1、在子组件调用父组件方法,并把组件实例回传给父组件(已经存储了子组件实例)
2、通过实例调用子组件的方法
父组件 Parent.js
import react,{ Component } from 'react';
import ChildPage from './Child'

export default class Parent extends Component{
  constructor(props){
    super(props)
    this.state = { } //声明变量
  }

  render(){
    return(
        <div className="ParentBig">
          <div onClick={ this.getChildFun }>点击</div>
          // 把子组件的this指针挂载成父组件的一个变量
          <ChildPage onRef={ this.getChildRef }></ChildPage>
        </div>
    )
  }
  //获取子组件实例
  getChildRef = ( ref ) => { 
     this.childExample = ref;
  }
  //父组件通过子组件回传的实例调用子组件方法
 getChildFun = () => {
     this.childExample.getValue();
 }
}
子组件 Child.js
import react,{ Component } from 'react';

export default class Parent extends Component{
  constructor(props){
    super(props)
    this.state = { } //声明变量
  }

  render(){
    return <div></div>
  }
  
  componentDidMount(){
      //返回子组件实例
     this.props.onRef( this );
  }
  //子组件方法
  getValue = () => {
      console.log('sssss')
  }

}

相关文章

网友评论

      本文标题:父组件调用子组件方法

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