React の usePortal フック

ReactReactBeginner
今すぐ練習

This tutorial is from open-source community. Access the source code

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

この実験では、React における usePortal フックの使用方法を検討します。このフックの目的は、親コンポーネントの外で子コンポーネントをレンダリングできるポータルを作成することです。useState()useCallback()、および useEffect() フックを使用してポータルを作成および管理する方法、ならびに ReactDOM.createPortal()ReactDOM.unmountComponentAtNode() を使用してポータルをレンダリングおよび削除する方法を学びます。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("React")) -.-> react/StateManagementGroup(["State Management"]) react(("React")) -.-> react/FundamentalsGroup(["Fundamentals"]) react(("React")) -.-> react/AdvancedConceptsGroup(["Advanced Concepts"]) react/FundamentalsGroup -.-> react/jsx("JSX") react/AdvancedConceptsGroup -.-> react/hooks("React Hooks") react/StateManagementGroup -.-> react/use_state_reducer("Using useState and useReducer") subgraph Lab Skills react/jsx -.-> lab-38403{{"React の usePortal フック"}} react/hooks -.-> lab-38403{{"React の usePortal フック"}} react/use_state_reducer -.-> lab-38403{{"React の usePortal フック"}} end

React usePortal フック

VM には既に index.htmlscript.js が用意されています。一般的には、script.jsstyle.css にのみコードを追加すればよいです。

親コンポーネントの外で子コンポーネントをレンダリングするポータルを作成するには、次の手順に従います。

  1. useState() フックを使用して、ポータルの render()remove() 関数を保持する状態変数を作成します。
  2. ReactDOM.createPortal()ReactDOM.unmountComponentAtNode() を使用して、ポータルとそれを削除する関数を作成します。useCallback() フックを使用して、これらの関数を createPortal() としてラップしてメモ化します。
  3. useEffect() フックを使用して、el の値が変更されるたびに createPortal() を呼び出し、状態変数を更新します。
  4. 最後に、状態変数の render() 関数を返します。

以下は、例としての実装です。

const usePortal = (el) => {
  const [portal, setPortal] = React.useState({
    render: () => null,
    remove: () => null
  });

  const createPortal = React.useCallback((el) => {
    const Portal = ({ children }) => ReactDOM.createPortal(children, el);
    const remove = () => ReactDOM.unmountComponentAtNode(el);
    return { render: Portal, remove };
  }, []);

  React.useEffect(() => {
    if (el) portal.remove();
    const newPortal = createPortal(el);
    setPortal(newPortal);
    return () => newPortal.remove(el);
  }, [el]);

  return portal.render;
};

このフックを使用するには、必要な DOM 要素を引数として usePortal() を呼び出すコンポーネントを作成します。このコンポーネントは、返された render() 関数を使用して、ポータル内にコンテンツをレンダリングできます。

const App = () => {
  const Portal = usePortal(document.querySelector("title"));

  return (
    <p>
      Hello world!
      <Portal>Portalized Title</Portal>
    </p>
  );
};

ReactDOM.createRoot(document.getElementById("root")).render(<App />);

右下隅の「Go Live」をクリックして、ポート 8080 でウェブサービスを実行してください。その後、Web 8080 タブを更新して、ウェブページをプレビューできます。

まとめ

おめでとうございます!あなたは React usePortal フックの実験を完了しました。あなたの技術を向上させるために、LabEx でさらに多くの実験を行って練習してください。