簡體   English   中英

在 Reactjs 中將組件作為道具傳遞

[英]Pass component as a prop in Reactjs

我有一篇文章展示了如何將組件作為道具傳遞,但我無法讓它工作,有人可以幫我嗎?

這是我得到的例子。

import React from "react";
import Foo from "./components/Foo";
import Bar from "./components/Bar";

const Components = {
  foo: Foo,
  bar: Bar
};

export default block => {
  // component does exist
  if (typeof Components[block.component] !== "undefined") {
    return React.createElement(Components[block.component], {
      key: block._uid,
      block: block
    });
  }
}

這是我的代碼

我有一個名為 routes.js 的文件,其中包含名為 routes 的 state。

var routes = [
  {
    path: "/user-profile",
    name: "Quem Somos",
    icon: "FaIdBadge",
    component: UserProfile,
    layout: "/admin"
  }

還有另一個名為 Sidebar 的組件,我在其中接收路由並需要根據“路由”道具中配置的內容更改圖標。

const Components = {
      fa:FaIdBadge
    }

<i>{prop => Components(prop.icon)}</i>

但是無法識別帶有圖標的屬性。

你很接近。

選擇類型作為運行時

import React from 'react';
import { PhotoStory, VideoStory } from './stories';

const components = {
  photo: PhotoStory,
  video: VideoStory
};

function Story(props) {
  // Correct! JSX type can be a capitalized variable.
  const SpecificStory = components[props.storyType];
  return <SpecificStory story={props.story} />;
}

所以更具體到你的例子

// component map in the file for lookup
const components = {
  fa: FaIdBadge,
}

...

  // In the render function
  // fetch the component, i.e. props.icon === 'fa'
  const IconComponent = components[props.icon];

  ...

  <IconComponent />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM