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

 

// 父組件
class Parent extends Component {
    handleChild = ()=> {
        this.$Child.childMethod();    // 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);    // 調用父組件傳入的函數,把自身賦給父組件
    }
    // 定義一個子組件方法
    childMethod = ()=> {
        alert('我是子組件中的方法!');
    }
    render() {
        return (<div></div>)
    }
}

 

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