gpt4 book ai didi

react-native - react native 矢量图标 - 动态类型

转载 作者:行者123 更新时间:2023-12-04 01:42:07 25 4
gpt4 key购买 nike

我正在使用不同类型的 React Native 矢量图标 - Material 和 FontAwesome,具体取决于特定图标的可用性。我想创建一个通用组件来包装整个应用程序中图标的使用。到目前为止,我有:

import React from 'react';
import Icon from "react-native-vector-icons/FontAwesome";
import {theme} from "../../../styles/style";

/**
* Common reusable icon component
* @param props
* @returns {*}
*/
const icon = (props) => {
return (
<Icon
size={theme.SIZE_ICON}
color={theme.BACKGROUND_ICON_COLOR}
{...props}
style={props.style}/>
);
};

export default icon;

仅适用于 FontAwesome,我如何根据例如使其动态化prop 参数以便我可以在需要时使用 Material 图标?注意:我不想为每种类型创建单独的组件,例如IconMaterial、IconFontAwesome 等。无论类型如何,我都希望组件的名称为 Icon。那可能吗?

最佳答案

你可以传递一个名为 iconFamily 的 Prop 到您的图标组件:

在您的图标组件中,您正在导入您想要使用的所有字体,例如:

import IconFA from "react-native-vector-icons/FontAwesome";
import IconMA from "react-native-vector-icons/Material";

然后在 Icon 的渲染函数中:
  const Icon = (props) => {

renderIcon = () => {
if (props.iconFamily == "FA") {
return (
<IconFA
size={23}
{...props}
style={props.style}/>
);
}
if (props.iconFamily == "MA") {
return (
<IconMA
size={23}
{...props}
style={props.style}/>
);
}
}
return (
renderIcon()
)
}

当您使用自定义图标组件时,您只需指定 iconFamily 属性:
 <Icon iconFamily="FA" name="home" color="green" /> 
<Icon iconFamily="MA" name="code" color="red" />

输出:

output

完整的工作示例:

https://snack.expo.io/@tim1717/humiliated-hummus

关于react-native - react native 矢量图标 - 动态类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56914404/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com