親コンポーネントから子要素メソッドを呼び出すフック


フックの親コンポーネントから子コンポーネントメソッドを呼び出すにはReact.forwardRef and React.useImperativeHandle 反応からのフック.

反応する。フォワードルフ


反応する.ForreDrefは、ツリー内の他のコンポーネントに受信するref属性を転送する反応コンポーネントを作成します.このテクニックはあまり一般的ではありませんが、2つのシナリオで特に有用です.
  • Forwarding refs to DOM components
  • Forwarding refs in higher-order-components
  • 反応する.Forwardrefはレンダリング関数を引数として受け取ります.反応は2つの引数として小道具とrefでこの機能を呼びます.この関数は、反応ノードを返します.

    詳細はforwarding refs .

    反応する。使用法


    UseSeriativeHandleはrefを使用するときに親コンポーネントに公開されているインスタンス値をカスタマイズします.UseSimativeHandleを使用する必要がありますforwardRef :

    ここで、子メソッドを呼ぶ重要な部分があります。


    ここで、子要素を親にレンダリングし、React.useRef これにより、getAlert ()関数が呼び出されます.
    import React from "react";
    const { forwardRef, useRef, useState, useImperativeHandle } = React;
    
    // We need to wrap component in `forwardRef` in order to gain
    // access to the ref object that is assigned using the `ref` prop.
    // This ref is passed as the second parameter to the function component.
    const Child = forwardRef((props, ref) => {
      const [state, setState] = useState(0);
    
      const getAlert = () => {
        alert("getAlert from Child");
        setState(state => state + 1)
      };
    
      // The component instance will be extended
      // with whatever you return from the callback passed
      // as the second argument
      useImperativeHandle(ref, () => ({
        getAlert,
      }));
    
      return (
        <>
          <h1>Count {state}</h1>
          <button onClick={() => getAlert()}>Click Child</button>
          <br />
        </>
      );
    });
    
    export const Parent = () => {
      // In order to gain access to the child component instance,
      // you need to assign it to a `ref`, so we call `useRef()` to get one
      const childRef = useRef();
    
      return (
        <div>
          <Child ref={childRef} />
          <button onClick={() => childRef.current.getAlert()}>Click Parent</button>
        </div>
      );
    };
    
    
    
    子要素がレンダリングされ、React.useRef チルドルフという名前.親コンポーネントで作成されたボタンは、子コンポーネント関数Childrfを呼び出すために使用されます.カレント.getAlert ()

    リファレンス


    https://reactjs.org/
    https://stackoverflow.com/