SoFunction
Updated on 2025-04-07

React implements two ways to write parent components to call child components

Preface

React communication is divided into many types, such as father-son communication, brother communication, etc. Here we will briefly talk about father-son communication. Parent-son communication is divided into: the parent component calls the methods in the child component; the child component calls the methods in the child component. The child can solve the problem by tying the parent one porps. Here we will focus on the parent component calling the child component. Without further ado, just upload the code:

Functional writing:

Method 1:

import React, { useImperativeHandle, forwardRef } from "react";
 
function Child(props, ref) {
  useImperativeHandle(ref, () => {
    return {
      onClick: handleClick,
    }
  });
 
  const handleClick = () => {
    alert('Clicked');
  }
 
  return (
    <button>I'm the button</button>
  )
}
 
export default forwardRef(Child);

import React, { useRef } from "react";
import Child from './child';
 
function Calling() {
  const nRef = useRef();
 
  const handleClick = () => {
    ();
  }
 
  return (
    <div>
      <button onClick={handleClick}>Call the child component after clicking</button>
      <Child ref={nRef} />
    </div>
  )
}
 
export default Calling;

The parent tone uses ref, in short: use hook function to bind the child component's custom method to it. Three hooks are used here: useRef, useImperativeHandle, and forwardRef.

: The parent component uses useRef to pass to the child component through the parameter (the parameter name here must be ref)

: Add the function customized by the child component to the ref of the parent component. Note that here, the first parameter is ref and the second parameter is an object (that is, the method called in the parent component or the attribute or value to be obtained).

: Pass the referenced ref to the child component. At this time, the first parameter received by the child component is porps and the second parameter is ref.

Since the parameter passed to the subcomponent is the ref keyword above, there must be a method for receiving in the subcomponent.

Method 2:

import React from "react";
 
function Child(props) {
  const handleClick = () => {
    alert('Clicked');
  }
 
   = {
    onClick: handleClick,
  }
 
  return (
    <button>I'm the button</button>
  )
}
 
export default Child;

import React from "react";
import Child from './child';
 
function Calling() {
  const nRef = {};
 
  const handleClick = () => {
    ();
  }
 
  return (
    <div>
      <button onClick={handleClick}>Call the child component after clicking</button>
      <Child nref={nRef} />
    </div>
  )
}
 
export default Calling;

(Solution 2)

import React, { useRef } from "react";
import Child from './child';
 
function Calling() {
  const nRef = useRef();
 
  const handleClick = () => {
    ();
  }
 
  return (
    <div>
      <button onClick={handleClick}>Call the child component after clicking</button>
      <Child nref={nRef} />
    </div>
  )
}
 
export default Calling;

Please pay attention to the differences between the two files in Method 2. It is nothing more than changing the empty object to useRef. Why do you need to write this way? Are there any advantages to writing this way? When the code volume is the same, one thing you should think about: performance. Of course, choose which one is better. I compared the two index files in method two (actually, it is a comparison between empty objects and useRef). There is no need to explain too much in empty objects: reference type...; let's focus on explaining useRef: it can help us cache data and return a ref object, which is used to store data. The returned ref object will not be recreated (the implication is that no matter how many times his father renders it, the object points to the address only at the most original one). The change of the value here will not cause the component to be re-reduced, and the component will not be updated due to state update (that is, the component state has changed, and the changed state can be saved here). If you only want to save the state, it does not affect the view update, and you can obtain and update the state synchronously, it is recommended to use useRef.

Think about it, if his grandfather kept rendering and using const nRef = {}; will he constantly assign a new address to nRef. The previous address will only be released by the garbage collection mechanism (if you don’t understand the garbage collection mechanism, please flip through it). No matter how many times his grandfather renders it, there will be only one address in the end.

Class component writing:

Method 1:

import React , { Component } from "react"
 
class Child extends Component {
	handleClick = () => {
           alert('Clicked');
        }
 
	render(){
		return (<div>Subcomponents</div>);
	}
}

class Parent extends Component {
	constructor(props) {
	    super(props);
	 	 = ();
	}
 
	handleOnClick = ()=>{
		();
	}
	render(){
		return (<div>
			<button onClick={}>click</button>
			<Child ref={}></Child>	
		</div>);
	}
}

Method 2:

import React , { Component } from "react"
 
class Child extends Component {
        componentDidMount(){
            &amp;&amp; (this);
	}
 
	handleClick = () =&gt; {
           alert('Clicked');
        }
 
	render(){
		return (&lt;div&gt;Subcomponents&lt;/div&gt;);
	}
}

class Parent extends Component {
	handleOnClick = ()=>{
		();
	}
 
	render(){
		return (<div>
			<button onClick={}>click</button>
			<Child onRef={ data =>  = data }></Child>	
		</div>);
	}
}

Compare two methods of class components:

Method 1: Simple and easy to understand, the disadvantage is: If the subcomponent is nested with higher-order components, then it cannot point to the real subcomponent.

Method 2: The writing method is simpler and easier to understand and rough. The disadvantage is that it requires custom props attributes.

There is actually another method three here, idea: everyone can use advanced components + reverse inheritance to implement it.

This is the end of this article about the two writing methods of React implementing the parent component to call child components. For more related React parent tone content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!