簡體   English   中英

如何根據道具值加載反應組件

[英]How to load react component based on prop value

我正在使用帶有“ @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' />  

代碼 https://codesandbox.io

我是巴西人,因此我會說葡萄牙語,但我會使用翻譯來幫助您。

您可以執行以下操作:

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 ,因為如果它不正確,它可能會出錯。 為了防止你可以事先做一些測試。

我寧願以不同的方式來做。 我會將組件本身作為道具傳遞給 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

暫無
暫無

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

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