0

我有一篇文章展示了如何将组件作为道具传递,但我无法让它工作,有人可以帮我吗?

这是我得到的例子。

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。

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>

但是无法识别带有图标的属性。

4

1 回答 1

1

你很接近。

选择类型作为运行时

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 />
于 2020-07-30T04:46:29.213 回答