CurrencySelectorコンポーネントは、利用可能なオプションのリストから支払い通貨を選択するための、使いやすいインターフェースを提供します。各通貨をロゴ、シンボル、関連する支払い方法とともに表示し、ユーザーが簡単に選択できるようにします。このコンポーネントは通常、より大きな支払いフォームやチェックアウトフォーム内で使用されます。
Props
| Prop | Type | Description | Required |
|---|---|---|---|
value | string | 現在選択されている通貨のIDです。親コンポーネントのstateで管理する必要があります。 | Yes |
currencies | TPaymentCurrency[] | 選択可能なオプションとして表示される、利用可能な通貨オブジェクトの配列です。 | Yes |
onChange | (currencyId: string, methodId?: string) => void | ユーザーが通貨を選択したときに実行されるコールバック関数です。新しい通貨IDと、オプションで関連する支払い方法のIDを受け取ります。 | Yes |
TPaymentCurrency 型
currencies propは、以下の構造を持つオブジェクトの配列を想定しています:
TPaymentCurrency
export type TPaymentCurrency = {
id: string; // 通貨オプションの一意の識別子
logo: string; // 通貨/メソッドのロゴのURL
name: string; // 通貨の表示名
symbol: string; // 通貨記号(例:'$'、'€')
method: { // 関連する支払い方法
id: string;
name: string;
};
};使用例
以下はCurrencySelectorコンポーネントを実装する基本的な例です。親コンポーネントで選択された通貨のstateを管理し、利用可能な通貨のリストを提供する必要があります。
@blocklet/payment-reactコンポーネントはPaymentProvider内で動作するように設計されており、PaymentProviderが必要なテーマとコンテキストを提供します。コンポーネントが適切にラップされていることを確認してください。
MyCurrencySelectorComponent.tsx
import React, { useState } from 'react';
import { PaymentProvider } from '@blocklet/payment-react';
import { CurrencySelector } from '@blocklet/payment-react/components';
import type { TPaymentCurrency } from '@blocklet/payment-types';
import { useSessionContext } from '@/hooks/session-context'; // このインポートパスをあなたのプロジェクト構造に合わせて調整してください
// デモンストレーション用のモックデータ
const mockCurrencies: TPaymentCurrency[] = [
{
id: 'usd_xxxxxx',
logo: 'https://path-to-your/usd-logo.png',
name: 'US Dollar',
symbol: 'USD',
method: {
id: 'stripe_yyyyy',
name: 'Stripe',
},
},
{
id: 'eth_zzzzzz',
logo: 'https://path-to-your/eth-logo.png',
name: 'Ethereum',
symbol: 'ETH',
method: {
id: 'crypto_aaaaa',
name: 'Crypto Payment',
},
},
];
function MyCurrencySelectorComponent() {
const [selectedCurrency, setSelectedCurrency] = useState<string>(mockCurrencies[0].id);
const handleCurrencyChange = (currencyId: string, methodId?: string) => {
console.log(`選択された通貨: ${currencyId}, メソッド: ${methodId}`);
setSelectedCurrency(currencyId);
};
return (
<div>
<h3>通貨を選択</h3>
<CurrencySelector
value={selectedCurrency}
currencies={mockCurrencies}
onChange={handleCurrencyChange}
/>
</div>
);
}
// あなたのアプリのエントリーポイント
export default function App() {
const { session, connectApi } = useSessionContext();
if (!session || !connectApi) {
return <div>読み込み中...</div>;
}
return (
<PaymentProvider session={session} connectApi={connectApi}>
<MyCurrencySelectorComponent />
</PaymentProvider>
);
}この例では:
TPaymentCurrency構造に従うmockCurrencies配列を定義します。MyCurrencySelectorComponentはuseStateフックを使用してselectedCurrencyを追跡します。handleCurrencyChange関数は、新しい通貨が選択されたときにstateを更新し、新しい値をログに出力します。CurrencySelectorは制御されたコンポーネントであり、そのvalueとonChangepropsは親のstateによって管理されます。- コンポーネント全体が
PaymentProviderでラップされ、適切なレンダリングとスタイリングに使用されるMaterial-UIテーマへのアクセスを確保します。