【问题标题】:How to load react component based on prop value如何根据道具值加载反应组件
【发布时间】:2021-06-03 03:23:25
【问题描述】:

我正在使用带有 '@fluentui/react-northstar' 库的图标组件,如下所示

import { QnaIcon } from '@fluentui/react-northstar'
const Example1 = () => (
  <>
    <QnaIcon size="large" />
  </>
) 

现在我必须在图标名称来自类似这样的道具时动态加载图标组件

import React from 'react'
import { Button, TeamCreateIcon   } from '@fluentui/react-northstar' 

const Example2 = ({iconName}) => {
 
const MyIcon = <iconName /> ; //here I need to convert string to component 

return (
  <div >
     <Button icon={<TeamCreateIcon />} title="Create" />
     // Here I need set it
     <Button icon={<MyIcon />} title="Create" />    
  </div>
)} 
<Example2 iconName='QnaIcon' />  

code https://codesandbox.io

【问题讨论】:

  • 你能在 props 中传递图标本身而不只是图标名称吗?
  • @squillman 我必须从 json 传递图标名称,它是可配置的
  • 我只是在想其他组件可以确定图标,因为它已经确定了您需要哪个。将逻辑放在一个地方。您仍然可以在其他组件中解析 JSON 以获取图标并将其传递给该组件。

标签: reactjs typescript fluentui-react


【解决方案1】:

我是巴西人,因此我会说葡萄牙语,但我会使用翻译来帮助您。

你可以做的是:

import React from 'react'
import { Button, TeamCreateIcon   } from '@fluentui/react-northstar' 

const Example2 = ({iconName}) => {

const ICONS = {
  iconLike: <YourLikeIcon/>,
  iconMenu: <YourMenuIcon/>,
}

return (
  <div >
     <Button icon={<TeamCreateIcon />} title="Create" />
     // Here I need set it
     <Button icon={ICONS[iconName]} title="Create" />    
  </div>
)} 

但是你必须小心iconName,因为如果它不正确,它可能会出错。为了防止你可以事先做一些测试。

【讨论】:

【解决方案2】:

我宁愿以不同的方式来做。我会将组件本身作为道具传递给 Example2

<Example2>
  <Icon/>
</Example2>

在实际的组件中,我会使用props.children,其中包含我们上面提到的子组件

import React from 'react'

const Example2 = () => {
 

return (
  <div >
     <Button icon={props.children} title="Create" />
     <Button icon={<MyIcon />} title="Create" />    
  </div>
)} 

编辑

也包括代码框链接

https://codesandbox.io/s/fluent-ui-example-forked-p5lkk?file=/example.js

【讨论】:

猜你喜欢
  • 2020-10-09
  • 2019-07-26
  • 2021-03-19
  • 1970-01-01
  • 1970-01-01
  • 2019-09-03
  • 2021-05-27
  • 2019-12-27
  • 1970-01-01
相关资源
最近更新 更多