reactjs 在Typescript对象中为某些枚举键传递关联值

tnkciper  于 2023-01-12  发布在  React
关注(0)|答案(1)|浏览(126)

我正在尝试遍历一个对象,其中键都是枚举中的case,值是any类型(使用Typescript)。当对象中的值是预定义的常量时,这可以很好地工作,但其中一个值需要使用提供的字符串来生成返回对象。有什么方法可以在Typescript中完成此操作吗?我将在下面展示我所做的事情的简化示例。

对象常量

export const injected = new InjectedConnector({
  supportedChainIds: [1, 3, 4, 5, 42],
});

export const walletconnect = new WalletConnectConnector({
  rpc: RPC_URLS,
  chainId: 1,
  bridge: 'https://bridge.walletconnect.org',
  qrcode: true,
});

export const walletlink = new WalletLinkConnector({
  url: RPC_URLS[1],
  appName: 'web3-react example',
  supportedChainIds: [1, 3, 4, 5, 42, 10, 137, 69, 420, 80001],
});

export const magic = (email: string) => {
  return new MagicConnector({
    apiKey: 'apiKey',
    chainId: 1,
    email: email,
  });
};

要在前端循环访问的枚举和对象

enum ConnectorNames {
  Injected = 'MetaMask',
  WalletConnect = 'WalletConnect',
  WalletLink = 'Coinbase Wallet',
  Magic = 'Email',
}

const connectorsByName: { [connectorName in ConnectorNames]: any } = {
  [ConnectorNames.Injected]: injected,
  [ConnectorNames.WalletConnect]: walletconnect,
  [ConnectorNames.WalletLink]: walletlink,
  // Would like to give magic an associated string value to pass into magic const above,
  // somehting like `magic(test@gmail.com)`
  [ConnectorNames.Magic]: magic,
};

前端TSX

const TestComponent = () => {
  const [connector, setConnector] = useState<any>(null);
  const testString = 'Hello, World!';
  return (
    <>
      {Object.keys(connectorsByName).map((name) => {
        // Would like to pass in test string to the connector/name in some way, and have magic
        // consume it and the other 3 enum cases that dont need the associated value ignore it
        const currentConnector =
          connectorsByName[name as keyof typeof connectorsByName];
        return (
          <div
            className=" bg-white rounded-lg p-4 hover:cursor-pointer min-w-[25vw]"
            key={name}
            onClick={() => {
              setConnector(currentConnector);
            }}
          ></div>
        );
      })}
    </>
  );
};

export default TestComponent;
fnvucqvd

fnvucqvd1#

必须对Object.keys() API的返回值使用类型Assert。请参见Why doesn't Object.keys return a keyof type in TypeScript?

enum ConnectorNames {
    Injected = 'MetaMask',
    WalletConnect = 'WalletConnect',
    WalletLink = 'Coinbase Wallet',
    Magic = 'Email',
}

const connectorsByName: Record<ConnectorNames, any> = {
    [ConnectorNames.Injected]: () => 1,
    [ConnectorNames.WalletConnect]: () => '2',
    [ConnectorNames.WalletLink]: () => true,
    [ConnectorNames.Magic]: () => null,
};

(Object.keys(connectorsByName) as ConnectorNames[]).map((name) => {
    const currentConnector = connectorsByName[name];
})

打字机游戏场

相关问题