我們使用 usedapp
npm install @usedapp/core ethers
ConnectButton.tsx
import React, { useEffect } from 'react';
import { useEthers, useEtherBalance } from '@usedapp/core';
import { formatEther } from '@ethersproject/units';
import { Button, Box, Text } from '@chakra-ui/react';
import Identicon from './Identicon';
type Props = {
handleOpenModal: any;
handleUser: any;
};
export function ConnectButton({ handleOpenModal, handleUser }: Props) {
const { activateBrowserWallet, account } = useEthers();
const etherBalance = useEtherBalance(account);
function handleConnectWallet() {
activateBrowserWallet();
}
useEffect(() => {
if (account) {
handleUser(account);
}
}, [account]);
/// 帳號是否存在(是否連接)
return account ? (
<Box
display="flex"
alignItems="center"
background="gray.700"
borderRadius="xl"
py="0"
>
顯示帳號相關資訊
</Box>
) : (
<Button onClick={handleConnectWallet}>Connect to a wallet
連接帳號
</Button>
);
}
這邊顯示縮短的 account 以及使用者頭像
<Text color="white" fontSize="md" fontWeight="medium" mr="2">
{account &&
`${account.slice(0, 6)}...${account.slice(
account.length - 4,
account.length
)}`}
</Text>
<Identicon />
const { isOpen, onOpen, onClose } = useDisclosure();
const [net, setNet] = useState(false);
const [X_API_KEY, setApiKey] = useState(null); //X_API_KEY
const [account, setAccount] = useState(null);
const { items, loadItems, setApiMode, setKey, setOwner } =
useCollectableService();
useEffect(() => {
setApiMode(net);
setKey(X_API_KEY);
setOwner(account);
}, [account, net, X_API_KEY]);
如果有不懂的地方可以偷看完成的DEMO