乐闻世界logo
搜索文章和话题

How to call child component method from parent component in react?

1个答案

1

In React, parent components typically call child component methods through several steps, with the key being to use ref to access the child component instance and invoke its methods. The following are the specific steps to implement this:

Step 1: Creating the Child Component

First, we define a child component and create a method intended for invocation from the parent component. For example, we define a ChildComponent with a method named childMethod:

jsx
import React from 'react'; class ChildComponent extends React.Component { childMethod() { alert('This child component method is called'); } render() { return <div>Child Component</div>; } } export default ChildComponent;

Step 2: Using ref in the Parent Component

In the parent component, we use React's ref to reference the child component. This enables direct access to the child component's methods and properties from the parent component.

jsx
import React from 'react'; import ChildComponent from './ChildComponent'; class ParentComponent extends React.Component { constructor(props) { super(props); // Create ref this.childRef = React.createRef(); } callChildMethod = () => { // Use ref to invoke the child component's method this.childRef.current.childMethod(); } render() { return ( <div> <ChildComponent ref={this.childRef} /> <button onClick={this.callChildMethod}>Call Child Component Method</button> </div> ); } } export default ParentComponent;

Explanation

In the above example, we first create a ref instance in the ParentComponent constructor and pass it to ChildComponent during rendering. This way, this.childRef.current references the ChildComponent instance, allowing us to invoke this.childRef.current.childMethod().

This approach is highly effective for direct communication between React components, particularly when the child component has internal state or methods that need triggering from the parent. Additionally, using ref is one of the officially recommended methods for directly accessing the child component instance and methods from the parent component.

2024年6月29日 12:07 回复

你的答案