UNPKG

@blocklet/payment-react

Version:

Reusable react components for payment kit v2

91 lines (76 loc) 3.9 kB
# 表單元素 `@blocklet/payment-react` 程式庫提供了一系列精細的輸入元件,旨在簡化自訂支付和聯絡資訊表單的建立。這些元素在建構時考慮了驗證和使用者體驗,並與 `react-hook-form` 順利整合,為資料收集提供了強大而靈活的解決方案。 每個元件都被設計成一個獨立的單元,讓您可以將它們組合成符合您特定需求的複雜表單。以下是可用表單元素的概覽。 <x-cards data-columns="2"> <x-card data-title="AddressForm" data-icon="lucide:map-pin" data-href="/components/ui/form-elements/address-form"> 一個預先建構的表單,用於收集帳單地址詳細資訊,並具有特定國家/地區的驗證功能。 </x-card> <x-card data-title="PhoneInput" data-icon="lucide:phone" data-href="/components/ui/form-elements/phone-input"> 一個國際電話號碼輸入框,整合了國家/地區代碼選擇器和驗證功能。 </x-card> <x-card data-title="CountrySelect" data-icon="lucide:globe" data-href="/components/ui/form-elements/country-select"> 一個可搜尋的下拉式選單,用於選擇國家/地區,附有國旗和適合行動裝置的使用者介面。 </x-card> <x-card data-title="CurrencySelector" data-icon="lucide:coins" data-href="/components/ui/form-elements/currency-selector"> 一個允許使用者從可用選項中選擇其偏好支付貨幣的元件。 </x-card> </x-cards> ## 常見使用模式 這些表單元素旨在與 `react-hook-form` 中的 `FormProvider` 一起使用。您可以組合它們來建立全面的表單,以擷取交易所需的所有必要資訊。雖然每個元件都有自己的一組屬性,但它們共享一個通用的整合模式。 以下是一個基本範例,說明如何組合多個表單元素來建立使用者資訊表單: ```jsx MyCustomForm.tsx icon=logos:react import { FormProvider, useForm } from 'react-hook-form'; import { AddressForm, PhoneInput, CurrencySelector } from '@blocklet/payment-react'; import { Button, Stack } from '@mui/material'; // 假設 availableCurrencies 是從您的後端獲取的 const availableCurrencies = [ { id: 'usd_xxx', name: 'USD', symbol: 'USD', logo: 'url/to/usd_logo.png', method: { id: 'stripe', name: 'Stripe' }, }, // ... 其他貨幣 ]; function MyCustomForm() { const methods = useForm({ defaultValues: { currency: 'usd_xxx', phone_number: '', billing_address: { line1: '', city: '', state: '', postal_code: '', country: 'US', // 使用 ISO2 代碼 }, }, }); const onSubmit = (data) => { console.log('表單資料已提交:', data); }; return ( <FormProvider {...methods}> <form onSubmit={methods.handleSubmit(onSubmit)}> <Stack spacing={2}> <CurrencySelector value={methods.watch('currency')} currencies={availableCurrencies} onChange={(currencyId) => methods.setValue('currency', currencyId)} /> <PhoneInput name="phone_number" label="電話號碼" required /> <AddressForm mode="required" stripe={false} /> <Button type="submit" variant="contained"> 提交 </Button> </Stack> </form> </FormProvider> ); } ``` 在此範例中,`CurrencySelector`、`PhoneInput` 和 `AddressForm` 被組合在一個表單中。`CurrencySelector` 被用作一個與表單狀態綁定的受控元件,而 `PhoneInput` 和 `AddressForm` 則是非受控元件,它們會自動將其欄位和驗證規則註冊到 `react-hook-form` 的上下文中。 ## 後續步驟 要了解每個元件的具體屬性和實作細節,請探索它們各自的說明文件頁面。 從 [AddressForm](./components-ui-form-elements-address-form.md) 開始,了解如何收集帳單資訊。