Call child method from parent

前端 未结 16 2462
长发绾君心
长发绾君心 2020-11-21 22:23

I have two components.

  1. Parent component
  2. Child component

I was trying to call child\'s method from Parent, I tried this way but couldn\

16条回答
  •  天命终不由人
    2020-11-21 23:24

    We can use refs in another way as-

    We are going to create a Parent element, it will render a component. As you can see, the component that will be rendered, you need to add the ref attribute and provide a name for it.
    Then, the triggerChildAlert function, located in the parent class will access the refs property of the this context (when the triggerChildAlert function is triggered will access the child reference and it will has all the functions of the child element).

    class Parent extends React.Component {
        triggerChildAlert(){
            this.refs.child.callChildMethod();
            // to get child parent returned  value-
            // this.value = this.refs.child.callChildMethod();
            // alert('Returned value- '+this.value);
        }
    
        render() {
            return (
                
    {/* Note that you need to give a value to the ref parameter, in this case child*/}
    ); } }

    Now, the child component, as theoretically designed previously, will look like:

    class Child extends React.Component {
        callChildMethod() {
            alert('Hello World');
            // to return some value
            // return this.state.someValue;
        }
    
        render() {
            return (
                

    Hello

    ); } }

    Here is the source code-
    Hope will help you !

提交回复
热议问题