React to call the parent component sub-assemblies

Click the button on the parent component method call subcomponents

Parent component:

import React, {Component} from 'react';
import ChildComponent from './child';
export default class ParentComponent extends Component {
    render() {
        return(
            <div>
                <ChildComponent onRefChild={this.onRefChild} />
                <button onClick={this.clickParent.bind(this)} >{'点击'}</button>
            </div>
        )
    }

    onRefChild = (ref) => {
        this.child = ref
    }

    clickParent = (e) => {
        this.child.childMethods()
    }

}

Subassembly:

import React, {Component} from 'react';
export default class ParentComponent extends Component {
    componentDidMount(){
        this.props.onRefChild(this)
    }

    childMethods = () => Alert ( 'subassembly is executed' )

    render() {
        return (<div> I sub-assembly </ div>)
     }

}

 

Guess you like

Origin www.cnblogs.com/0828-li/p/11011601.html