React 父組件調用子組件函數


父組件代碼

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

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM