javascript - 映射对象中的多个可能值 - React 组件
问题描述
我目前有一个组件,它接受一个 currencyCode 并返回相应国家的 SVG。我想扩展组件,以便我们希望按国家名称而不是货币代码进行搜索。当前传入组件的 props 是:
currencyCode - 类似于“AED”和 countryLabel - 类似于“阿拉伯联合酋长国”
import Afghanistan from "./CountryFlags/Afghanistan.js";
// condensed imports
const currencyCodeMap = {
AED: UnitedArabEmirates,
AFN: Afghanistan,
ALL: Albania,
AMD: Armenia,
AOA: Angola,
ARS: Argentina,
AUD: Australia,
AZN: Azerbaijan,
};
type Props = {
currencyCode?: string,
countryLabel?: string,
className?: string,
};
const CountryFlag = ({ currencyCode, countryLabel, className }: Props) => {
const FlagComponent = currencyCodeMap[currencyCode];
if (!FlagComponent) {
return <StyledIcon isOberonIcon={true} name={"countryFallback"} />;
}
return (
<StyledImageWrapper className={className}>
<FlagComponent />
</StyledImageWrapper>
);
};
我试图将我的 currencyCodeMap 更新为:
AED | "United Arab Emirates"
这样标签或代码都会返回一个标志,但没有乐趣。有什么建议么?
解决方案
AED | "United Arab Emirates"
不是有效的 JavaScript 语法。
为什么没有像这样的对象:
type CountryEntry = {
currencyCode: string,
countryLabel: string,
flagComponent: JSX.Element
}
然后有一个数组并用于.find()
获取组件。
它看起来像这样:
import Afghanistan from "./CountryFlags/Afghanistan.js";
type Props = {
currencyCode?: string,
countryLabel?: string,
className?: string,
};
type CountryEntry = {
currencyCode: string,
countryLabel: string,
flagComponent: JSX.Element
}
const flags: CountryEntry[] = [
{ currencyCode: "AFN", countryLabel: "Afghanistan", flagComponent: Afghanistan },
/* ... */
];
const CountryFlag = ({ currencyCode, countryLabel, className }: Props) => {
const countryEntry = flags.find(
(f) => f.countryLabel === countryLabel || f.currencyCode === currencyCode
);
if (!countryEntry) {
return <StyledIcon isOberonIcon={true} name={"countryFallback"} />;
} else {
const FlagComponent = countryEntry.flagComponent;
return (
<StyledImageWrapper className={className}>
<FlagComponent />
</StyledImageWrapper>
);
};
推荐阅读
- intellij-idea - IntelliJ IDEA 的 JVM 调试器内存视图
- rust - `UnsafeCell` 是 Rust 中的编译器优化障碍吗?
- json - 在 go 中解析自定义 JSON,类型动态确定
- javascript - 单击新图标时,地图图标不会恢复到正常大小
- html - 如何使用标签管理器跟踪与 Facebook 聊天插件的互动?
- css - 如何在移动设备上将 div 内的元素对齐为 2-3 行(响应式)
- go - 无需硬编码类型或将类型信息存储在数组中的类型检查
- reactjs - 使用 CRACO 禁用文件分块
- linux - 如何减去日期
- extjs - Ext.Msg 中 textarea 的占位符值