React high-order component parent component calls child component method

React high-order components are a technology for reusing component logic. Developers can enhance the functionality of a component through HOC and return it to the caller. Since the higher-order component itself is not a real component, but a function, it is not possible to directly call the method of the child component.

However, the function of the parent component calling the method of the child component can be realized through Ref.

Hooks used: useImperativeHandle(ref, createHandle, [deps])

Parameter Description:

1.ref: The ref object that needs to be assigned.

2.createHandle: The return value of the createHandle function is used as the value of ref.current.

3.[deps]: Dependency array, if the dependency changes, the createHandle function will be re-executed.

The introduction of useImperativeHandle on the React official website is also relatively short. To sum it up in one sentence: the child component can use useImperativeHandle to allow the parent component to output arbitrary data.

The specific implementation steps are as follows:

1. Define a Ref in the subcomponent, and expose the method that needs to be called through the useImperativeHandle() Hook, for example:

import React, { forwardRef, useImperativeHandle } from 'react';

const ChildComponent = forwardRef((props, ref) => {
  const handleClick = () => {
    console.log('ChildComponent clicked!');
  };

  useImperativeHandle(ref, () => ({
    handleClick
  }));

  return (
    <button onClick={handleClick}>点击</button>
  );
});

export default ChildComponent;

In the above code, we used the React.forwardRef() method to create a subcomponent, and then defined a Ref and a click event handler function handleClick() inside the component. Through the useImperativeHandle() Hook, we expose the handleClick method for use by the parent component.

2. Use Ref in the parent component to get the child component instance and call its method, for example:

import React, { useRef } from 'react';
import ChildComponent from './ChildComponent';

const ParentComponent = () => {
  const childRef = useRef(null);

  const handleButtonClick = () => {
    childRef.current.handleClick();
  };

  return (
    <div>
      <button onClick={handleButtonClick}>点击调用子组件方法</button>
      <ChildComponent ref={childRef} />
    </div>
  );
};

export default ParentComponent;

In the above code, we first use the React.useRef() method to create a Ref object childRef, and then define an event handler function handleButtonClick() inside the parent component. When the button is clicked, we call the method handleClick() exposed in the child component through childRef.current.handleClick().

To sum up, by using Ref to obtain the child component instance and call its method, the parent component can realize the function of calling the child component method.

Guess you like

Origin blog.csdn.net/weixin_39823006/article/details/130583259