父組件代碼
import React, { Component,Fragment } from 'react' import TeamInfo from '../../component/TeamInfo' export default class Team extends Component { constructor (props){ super(props) this.Child = React.createRef(); //// 創建一個ref去儲存DOM子元素 this.getTeamList = this.getTeamList.bind(this) } showTeamInfoView(){ this.Child.current.show() //調用子元素函數 show (括號里可以傳參) } render() { return ( <Fragment> <Button type="primary" className='btn' onClick={()=>{this.showTeamInfoView()}} icon={<PlusOutlined />}>新增</Button> // ref 綁定子元素 <TeamInfo ref={this.Child}></TeamInfo> </Fragment> ) }
子組件代碼
import React,{Component,Fragment} from 'react' class TeamInfo extends Component{ constructor(props){ super(props) this.show=this.show.bind(this) } show(){ console.log("被父元素調用的函數") } render(){ return( <Fragment> </Fragment> ) } } export default TeamInfo