# @getspot/spot-widget-react 中文文档

规范地址：https://npmcn.com/package/%40getspot/spot-widget-react/

版本：4\.8\.0
npm 元数据更新时间：2026-11-05T16:01:11.890Z
中文译文更新时间：2026-11-16T06:50:58.160Z
软件包许可：未声明

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40getspot/spot-widget-react
原文对照：https://npmcn.com/package/%40getspot/spot-widget-react/?lang=original

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：41.2 kB，8 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：1 个
- peer 依赖：react \>=18\.0\.0，react-dom \>=18\.0\.0，@types/react \>=18\.0\.0，@types/react-dom \>=18\.0\.0
- 首次发布：2025-04-25T19:39:56.528Z
- 最新版本发布：2026-10-29T16:29:14.531Z
- 近 30 天下载量：7985（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：56（近 12 个月 27 个）

## 中文简介

Spot 部件的回放包装

## 安装

```sh
npm install @getspot/spot-widget-react
```

也可以使用：`pnpm add @getspot/spot-widget-react`、`yarn add @getspot/spot-widget-react`、`bun add @getspot/spot-widget-react`

## README

# @ getspot/ spot- widget- react

对 Spot 退款担保部件进行响应组件包装 .

> **说明:** 此反应包装使用类型来自 [@ getspot/ spot- widget (英语)](https://www.npmjs.com/package/@getspot/spot-widget)。 。 。 .

### 密钥类型

-   `ApiConfig` - API配置(环境、伙伴、自定义端点)
-   `QuoteRequestData` - 引用单项或批次请求的数据
-   `SelectionData` - 用户选择数据以回调方式返回
-   `Quote` - 引用有定价和条件的答复数据
-   `Theme` - 样式定制选项

完整的类型定义见 [@ getspot/ spot-widget 文档](https://www.npmjs.com/package/@getspot/spot-widget)。 。 。 .

## 安装

```bash
npm install @getspot/spot-widget-react
```

## 快速启动

```tsx
import React from 'react';
import ReactSpotWidget from '@getspot/spot-widget-react';

function App() {
  return (
    <ReactSpotWidget
      apiConfig={{
        environment: 'production', // or 'sandbox' for testing
        partnerId: 'your-partner-id'
      }}
      quoteRequestData={{
        startDate: '2024-01-01T00:00:00Z',
        endDate: '2024-01-07T23:59:59Z',
        currencyCode: 'USD',
        eventType: 'Ski Trip',
        productType: 'Trip',
        productDuration: 'Trip',
        productPrice: 500,
        productId: 'ski-trip-2024',
        cartId: 'cart-123',
        productName: 'Aspen Ski Trip 2024'
      }}
      onOptIn={(data) => {
        console.log('User opted in:', data);
        // Handle opt-in (e.g., add to cart, track analytics)
      }}
      onOptOut={(data) => {
        console.log('User opted out:', data);
        // Handle opt-out (e.g., track analytics)
      }}
      onError={(error) => {
        console.error('Widget error:', error);
        // Handle errors (e.g., show fallback UI)
      }}
    />
  );
}
```

## 类型脚本支持

这个包包括了完整的TypeScript定义. 所有道具都是为更好的发展经验而打字.

## 推荐参考

### 必需的道具

| Prop | 类型 | 说明 |
| --- | --- | --- |
| `apiConfig` | `ApiConfig` | Spot API 配置,包括环境和伙伴ID |
| `quoteRequestData` | `QuoteRequestData` | 引用请求中包含产品和推车信息的数据 |

### 可选道具

| Prop | 类型 | 默认 | 说明 |
| --- | --- | --- | --- |
| `showTable` | `boolean` | `true` | 是否显示支付表 |
| `selection` | `SelectionEnum` | `'unselected'` | 部件的初始选择状态 |
| `theme` | `Theme` | `undefined` | 部件样式的主题定制选项 |

### 回调道具

| Prop | 类型 | 说明 |
| --- | --- | --- |
| `onQuoteRetrieved` | `(quote: Quote) => void` | 成功取回引号时已调用 |
| `onOptIn` | `(data: SelectionData) => void` | 当用户选择使用退款担保时, 调用已启动 |
| `onOptOut` | `(data: SelectionData) => void` | 当用户选择退出退款担保时, 调用已启动 |
| `onError` | `(error: ErrorData) => void` | 当引用检索时发生错误时, 调用已发射 |
| `onNoMatchingQuote` | `(data: NoQuoteData) => void` | 找不到匹配引号时, 调用已启动 |
| `onSelectionChange` | `(data: SelectionData) => void` | 当用户更改其选择( 选择进入或选择退出) 时, 调用已启动 |

## 使用参考文献

您可以使用 React refs 访问部件方法 :

```tsx
import React, { useRef } from 'react';
import ReactSpotWidget, { ReactSpotWidgetRef } from '@getspot/spot-widget-react';

function App() {
  const widgetRef = useRef<ReactSpotWidgetRef>(null);

  const handleUpdateQuote = async () => {
    const success = await widgetRef.current?.updateQuote({
      // new quote data
    });
    console.log('Quote updated:', success);
  };

  const handleGetSelection = () => {
    const selection = widgetRef.current?.getSelection();
    console.log('Current selection:', selection);
  };

  const handleValidateSelection = () => {
    const isValid = widgetRef.current?.validateSelection();
    console.log('Selection is valid:', isValid);
  };

  return (
    <div>
      <ReactSpotWidget
        ref={widgetRef}
        // ... props
      />
      <button onClick={handleUpdateQuote}>Update Quote</button>
      <button onClick={handleGetSelection}>Get Selection</button>
      <button onClick={handleValidateSelection}>Validate Selection</button>
    </div>
  );
}
```

## 查找方法

| 方法 | 返回类型 | 说明 |
| --- | --- | --- |
| `updateQuote(data)` | `Promise<boolean>` | 用新请求数据更新引文 |
| `getSelection()` | `SelectionData | null` | 获取当前用户选择 |
| `validateSelection()` | `boolean` | 验证用户已选择 |
| `destroy()` | `void` | 销毁部件实例并清理资源 |

## API 配置

这个 `apiConfig` prop 接受以下选项:

```tsx
{
  environment: 'production' | 'sandbox' | 'local',
  partnerId: string,
  customEndpoint?: string // Optional custom API endpoint
}
```

## 引用请求数据

这个 `quoteRequestData` 道克需要以下字段:

### 单引文格式

```tsx
{
  startDate: string,        // ISO 8601 date string
  endDate: string,          // ISO 8601 date string  
  currencyCode: 'USD' | 'CAD' | 'AUD',
  eventType: string,        // e.g., "Ski Trip", "Concert"
  productType: 'Pass' | 'Trip' | 'Registration',
  productDuration: 'Daily' | 'Seasonal' | 'Trip' | 'Event',
  productPrice: number,     // Price in specified currency
  productId: string,        // Unique product identifier
  cartId: string,           // Cart identifier
  productName: string,      // Human-readable product name
  participantDescription?: string // Optional participant details
}
```

### 批次引文格式

对于一车中的多件物品:

```tsx
{
  cartId: string,
  cartName: string,
  currencyCode: 'USD' | 'CAD' | 'AUD',
  items: Array<{
    // Same fields as single quote, minus cartId and currencyCode
    cartItemId?: string // Optional unique identifier for cart item
  }>
}
```

## 样式

使用 `theme` 道具 :

```tsx
<ReactSpotWidget
  theme={{
    primaryColor: '#007bff',
    borderRadius: '8px',
    fontFamily: 'Arial, sans-serif'
    // Add any CSS custom properties (without -- prefix)
  }}
  // ... other props
/>
```

## 处理错误

总是执行用于生产的错误处理 :

```tsx
<ReactSpotWidget
  onError={(error) => {
    // Log error for debugging
    console.error('Spot Widget Error:', error);
    
    // Show user-friendly message
    toast.error('Unable to load refund options. Please try again.');
    
    // Track error in analytics
    analytics.track('spot_widget_error', {
      message: error.message,
      status: error.status
    });
  }}
  onNoMatchingQuote={() => {
    // Handle case where no quote is available
    console.log('No refund guarantee available for this product');
  }}
  // ... other props
/>
```

## 兼容性

-   **反应**: 18.x (中文(简体) )
-   **类型脚本**: 5.x (韩语)
-   **节点.js**: 16岁以上

## 许可证

许可证信息见主包.

## 支助

支助请联系 [支持@ getspot.com](mailto:support@getspot.com)。 。 。 .

## 常见问题

### @getspot/spot-widget-react 是什么？

Spot 部件的回放包装

### 如何安装 @getspot/spot-widget-react？

在项目目录运行 npm install @getspot/spot-widget-react，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：react（\>=18\.0\.0）、react-dom（\>=18\.0\.0）、@types/react（\>=18\.0\.0）、@types/react-dom（\>=18\.0\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @getspot/spot-widget-react 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @getspot/spot-widget-react 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @getspot/spot-widget-react 可以商用吗？

@getspot/spot-widget-react 使用 未声明 许可。package\.json 没有声明许可证。没有许可证的代码默认保留全部权利，商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括，不构成法律意见，请以许可原文为准。

### @getspot/spot-widget-react 的下载量有多少？

根据 npm 官方下载统计，@getspot/spot-widget-react 在 2026/10/17 – 2026/11/15 这 30 天内被下载 7,985 次，日均约 266 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @getspot/spot-widget-react 还在维护吗？

最新版本 4\.8\.0 发布于 2026/10/30（17 天前）；至今共发布 56 个版本，其中过去 12 个月发布了 27 个；首次发布于 2025/04/26。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

