React父組件調用子組件中的方法


// 父組件
class Parent extends Component {
    handleChild = ()=> {
        this.$Child.childConsole();    // this上有了子組件方法
    }
    render() {
        return (
            <div>
                <Child onRef={(ref)=> {this.$Child=ref}} />
                <button onClick={this.handleChild}>調用子組件方法</button>
            </div>
        )
    }
}
// 子組件
class Child extends Component {
    componentDidMount() {
        this.props.onRef(this);    // 調用父組件傳入的函數,把自身賦給父組件
    }
    // 定義一個子組件方法
    childConsole = ()=> {
        console.log('我是子組件方法')
    }
    render() {
        return (
      <div>

      </div>
    ) }

 


免責聲明!

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



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