问题描述
我正在使用带有“@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' />
解决方法
我是巴西人,因此我会说葡萄牙语,但我会使用翻译来帮助您。
您可以执行以下操作:
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