在非.tsx页面中,我们过去常常这样枚举:
const enumUrl= {
xxx: [BRAND],
yyy: [BRAND],
};
在.tsx页面中,我想使用enum
。所以我创造了:
enum EnumUrl {
xxx = "https://example.com/",
yyy = "https://example.net"
}
在联合来文中:
Visit <a href={EnumUrl[BRAND}} target="_blank" rel="noopener noreferrer">
{EnumUrl[BRAND]}
</a>
然而,它说:
Element implicitly has an 'any' type because expression of type 'any' can't be used to index type 'typeof EnumUrl'.ts(7053)
然后,我阅读了这个可能的解决方案:https://stackoverflow.com/a/41970976/1580094,并执行了以下操作:
enum EnumUrl {
xxx = "https://example.com/",
yyy = "https://example.net"
}
var url : EnumUrl = EnumUrl[BRAND as keyof typeof EnumUrl];
...
Visit <a href={url[BRAND}} target="_blank" rel="noopener noreferrer">
{url[BRAND]}
</a>
控制台日志: console.log(url);// https://example.com/ console.log(urlBRAND);//未定义的console.log(品牌);// xxx
但是这样做,<a
元素就完全从DOM中消失了。没有错误。
我做错了什么,我该如何解决呢?
发布于 2022-11-01 12:40:25
安恩博士似乎并不是你真正想要的。
哦,我明白了,乍一看,这就像是一个枚举:你有一组URL。这组URL可能实际上是一个枚举,类似于:
enum URLs {
A = "www.foo.com",
B = "www.bar.com"
}
问题来自于您如何使用这些值。因为您像使用映射一样使用"enum“:通过动态提供的键查找其中的值。Javascript/Typescript已经有了一个用于此目的的构造(实际上是两个),所以用enum来使用它
enum Brands {
'xxx',
'yyy'
}
// Note that www.foo.com and www.bar.com could be in
// *another* enum, and you could use the URL_MAP to
// connect the two enums. But either way you'll want the
// object for dynamic lookups
const URL_MAP = {
[Brands.xxx]: "www.foo.com",
[Brands.yyy]: "www.bar.com",
};
function foo(brand: Brands) {
return <a href={URL_MAP[brand]} />;
}
https://stackoverflow.com/questions/74275394
复制相似问题