1.概览
在web3开发的项目中几乎都需要和钱包进行交互。钱包替代了web2中的后端数据库。如何搭建一个美丽的钱包交互界面?直接先上效果图。
2.使用到的技术栈
- next.js
- wagmi(react hooks)
- ranbowkit(UI库)
- tailwindcss(css框架)
- daisyUI(UI库)
3.next.js的脚手架搭建
next.js号称是一个用于生产环境的React框架。如果你没有react.js的基础最好先大概了解下react.js。next.js在react的基础上增加了ssg和ssr的混合渲染、减少了配置成本、增加了增量静态生成等一系列的特性。
3.1 初始化next.js项目
npx create-next-app@latest --typescript
# or
yarn create next-app --typescript
3.2 添加tailwindcss库
tailwindcss是一个css框架可以大量减少css的代码量。如果你不需要、或者想手撸css、或者用bootstrap当然可以选择跳过这步。
npm install -D tailwindcss@latest postcss@latest autoprefixer@latest
我们还需要在next.js pages/_app.js 中添加基础的css包
// pages/_app.js
- import '../styles/globals.css'
+ import 'tailwindcss/tailwind.css'
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
export default MyApp
另外为了更加装逼我还加了daisyUI
npm i --save daisyui
装完之后需要略微修改下根目录下的tailwindcss配置文件即可
/** @type {import('tailwindcss').Config} */
module.exports = {
purge: ['./pages/**/*.{js,ts,jsx,tsx}', './components/**/*.{js,ts,jsx,tsx}'],
content: [],
theme: {
extend: {},
},
plugins: [require("daisyui")], //这是我们添加的内容.
}
4.rainbowkit配置
在我们的pages/_app.js中添加rainbowkit内容。
import { WagmiConfig, createClient, configureChains, defaultChains } from 'wagmi'
import { publicProvider } from 'wagmi/providers/public';
//rainbow kit UI framework.
import '@rainbow-me/rainbowkit/styles.css';
import {
getDefaultWallets,
RainbowKitProvider,
} from '@rainbow-me/rainbowkit';
const { chains, provider } = configureChains(defaultChains, [publicProvider()])
const { connectors } = getDefaultWallets({
appName: 'My RainbowKit App',
chains
});
const client = createClient({
autoConnect: true,
connectors,
provider,
})
这里首先初始化一个client对象。这个client对象有一些可选参数。
- autoConnect
- connectors
- providers
- storage
- webSocetProvider
具体解释可以参考下官方文档:wagmi.sh/
初始化之后我们就可以直接把client和chains传进去。
function MyApp({ Component, pageProps }) {
return (
<WagmiConfig client={client}>
<RainbowKitProvider chains={chains}>
<Component {...pageProps} />
</RainbowKitProvider>
</WagmiConfig>
)
}
基本的配置就完成了接下来在我们需要使用到的地方直接调用就行了。比如在我的header组件中的connect button。
import {
useConnectModal,
useAccountModal,
useChainModal,
} from '@rainbow-me/rainbowkit';
import { useAccount } from 'wagmi'
const { openConnectModal } = useConnectModal();
const { openAccountModal } = useAccountModal();
const { openChainModal } = useChainModal();
定义完成这个打开modal层的按钮之后只需要在我们的按钮上增加click事件就可以完成触发。
{isConnected ?
(<><button class="btn btn-sm btn-outline btn-primary ml-3 normal-case" onClick={openAccountModal}>Profile</button><button class="btn btn-sm btn-outline btn-primary ml-3 normal-case" onClick={openChainModal}>Chain</button></>)
:
(<button class="btn btn-sm btn-outline btn-primary ml-3 normal-case" onClick={openConnectModal}>connect wallet</button>)
}
5.完整的代码
github : github.com/coffiasd/de…