學習筆記:React父組件調用子組件方法

父組件:

import React, { Component } from "react";
import Child from './child'
export default class Parent extends Component {

componentDidMount(){
    //調用子組件
    this.child.test('參數')
}

onRef(ref){this.child = ref}

render() {
    return (
      <div>
        <Child onRef={this.onRef} />
      </div>
    );
  }
}

子組件:

import React, { Component } from "react";

export default class Child extends Component {

componentDidMount(){
    this.props.onRef(this)
}
//被調用方法
test(val){
    alert('我是測試方法'+val)
}

render() {
    return (
      <div>
            我是子組件
      </div>
    );
  }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章