動的コンポーネント


導入


もしあなたがVueと一緒に働いているなら、あなたはcomponent 下記のタグ
<script>
import CustomComponent from 'path-to-custom-component'
import AnotherComponent from 'path-to-another-component'

export default {
  components: {CustomComponent, AnotherComponent},

  data() {
    return {
      activeComponent: 'CustomComponent'
    }
  }
}
</script>

<template>
  <div>
   <component :is="activeComponent" />
  </div>
</template>

この記事では、動的にコンポーネントを動的に使用する方法を示します.
コーディング開始
あなたがすでに反応プロジェクトをセットしたと仮定するつもりです
まず、作成components あなたがまだ持っていないならば、ルートディレクトリのフォルダ.
インサイドcomponents フォルダー、新しいファイル名DynamicComponent.js 次のコードを追加します.
import React from "react";

/**
 * @desc the dynamic component is used to render various component dynamically
 * @params props: {
 *    useDefaultPath: this indicates that the component to be used is in the components folder if set to true else you would have to pass in a different component
 *    is: if `useDefaultPath` is true, you pass in the name of the component file or the path to the component in the component folder eg: NewComponent or BaseUI/NewComponent
 *    ...rest: the props to be passed into the new component
 * }
 */
const DynamicComponent = ({ is, useDefaultPath = true, ...rest }) => {
  return React.createElement(
    useDefaultPath ? require(`./${is}.js`).default : is,
    {
      ...rest,
    }
  );
};

export default DynamicComponent;

このコンポーネントを他のファイルに使用して、設定した条件に基づいて動的に異なるコンポーネントをレンダリングできます.
以下のコードは例です
import "./App.css";
import DynamicComponent from "./components/DynamicComponent";
import { useState } from "react";

function App() {
  const [activeComponent, setActiveComponent] = useState("SayHello");
  return (
    <div className="App">
      <header className="App-header">
        <DynamicComponent is={activeComponent} name="Sholademi Ayomikun" />

        <button
          onClick={() =>
            // Note that `SayHello` and `SayGoodbye` have been defined in the components folder
            setActiveComponent(
              activeComponent === "SayHello" ? "SayGoodbye" : "SayHello"
            )
          }
        >
          Toggle Component
        </button>
      </header>
    </div>
  );
}

export default App;

結論


記事はどのように使用できるかを示しますReact.createElement コンポーネントを動的にレンダリングするにはこのコードはhere .
ユースケースは、動的にアプリケーションのレイアウトを変更するか、別のビューで複数のタブがあります.
注意してくださいこれに反応するいくつかのアプローチがあります.
フォローオンミーgithub
また、購読してください.私はそこにコンテンツをディッシングを開始するために50加入者を取得しようとしている.