react 父組件調用子組件方法


import React from 'react'
import '../page1/header.css'
import { Table } from 'antd'
import Child from './child'//引入的子組件

export default class Header extends React.Component{
  constructor(){
  super()

  }

}

onRef = (ref) => {//react新版本處理方式
  this.child = ref
}
click = (e) => {
  this.child.myName()
}

render(){

  return (<div>

    <Child onRef={this.onRef} />

    <button onClick={this.click}>父組件調用子組件方法</button>

  </div>

  )

  }

//子組件

import React from 'react'

export default class Header extends React.Component{
  constructor(props){
    super(props)
  }

componentDidMount(){
  this.props.onRef(this)
}
myName = () => alert('父組件調用子組件方法成功')
render(){

return (
  <div className="header">
  </div>
)
}
}


免責聲明!

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



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