# @coveo/atomic-react 中文文档

规范地址：https://npmcn.com/package/%40coveo/atomic-react/

版本：3\.11\.51
npm 元数据更新时间：2026-11-09T14:22:08.013Z
中文译文更新时间：2026-11-10T20:58:44.669Z
软件包许可：Apache-2\.0

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

原始 npm 页面：https://www.npmjs.com/package/%40coveo/atomic-react
原文对照：https://npmcn.com/package/%40coveo/atomic-react/?lang=original
源码仓库：https://github.com/coveo/ui-kit

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

- 包体积（解压后）：17.3 MB，750 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：^20\.9\.0 \|\| ^22\.11\.0 \|\| ^24\.11\.0
- 运行依赖：2 个
- peer 依赖：react ^18 \|\| ^19，react-dom ^18 \|\| ^19，@types/react ^18 \|\| ^19，@coveo/headless ^3\.58\.1，@types/react-dom ^18 \|\| ^19
- 首次发布：2022-01-10T14:16:35.256Z
- 最新版本发布：2026-11-09T14:22:07.523Z
- 近 30 天下载量：15437（2026-10-11 至 2026-11-09，npm 官方下载统计）
- 已发布版本数：4434（近 12 个月 64 个）

## 中文简介

为原子元件库执行特定包装

## 安装

```sh
npm install @coveo/atomic-react
```

也可以使用：`pnpm add @coveo/atomic-react`、`yarn add @coveo/atomic-react`、`bun add @coveo/atomic-react`

## README

[![npm version](https://badge.fury.io/js/@coveo%2Fatomic-react.svg)](https://badge.fury.io/js/@coveo%2Fatomic-react)

# 原子反应

一个用于构建现代UIs与Coveo平台接口的React组件库. 原子反应是围绕核的包装 [原子](https://docs.coveo.com/en/atomic/latest/) 网络组件库.

将基于反应的项目(使用JSX)与基于Web的组件整合起来可能很困难. 这个项目旨在解决这一问题,使Atomic Web组件能够以对熟悉React的开发者更自然的方式被使用.

## 安装

`npm i @coveo/atomic-react`

### 替代安装- CDN

该图书馆还作为图书馆在科维奥CDN提供 `IIFE` (即时被引出函数表达式). 这是一种我们只建议用于快速原型和测试的方法,它可以用极少的前端工具来使用并构建工具.

我们建议不使用 `IIFE` 采用生产方法。 浏览器必须下载整个库代码,无论实际使用哪些组件. 我们建议在这种情况下使用捆绑机(例如Webpack).

你可以多读读这个方法 [下级](https://npmcn.com/package/%40coveo/atomic-react/#readme-usage-with-cdn-scripts--iife-)。 。 。 .

## 使用量

自从原子 反应在核心之上 [原子](https://docs.coveo.com/en/atomic/latest/) 网络组件库,绝大多数适用于核心原子的概念将适用于原子反应.

然而,仍然有一些特殊的考虑.

## 入境点

这个 `@coveo/atomic-react` 软件包显示下列切入点:

-   `@coveo/atomic-react`: 输出用于与Antomic React建立非商业搜索接口的部件和公用事业.
-   `@coveo/atomic-react/recommendation`: 出口与Antomic React建立非商业建议接口的部件和公用事业.
-   `@coveo/atomic-react/commerce`:出口与原子反应建立商业应用的部件和公用事业.

## 静态资产-语言和 SVGs

由于性能原因,所生成的JavaScript捆绑并不自动包括按需要加载的静态资产. 这影响了语言支持,以及包含的SVG图标的使用.

强制要求您提供与 Atomic React 一起分配的外部资产, 并将其纳入您的应用程序的公共目录。 举例来说,没有这个标签,应用程序中的标签会作为临时占位符出现.

公共目录的位置取决于您如何构建,配置和分发您的应用程序.

例如,对于使用 [创建反应应用](https://github.com/facebook/create-react-app),这意味着将语言和图标资产复制到 `./public` 目录.

```
cp -r node_modules/@coveo/atomic-react/dist/assets public/assets
cp -r node_modules/@coveo/atomic-react/dist/lang public/lang
```

必须尊重文件夹的分级,在下方有 SVG 图标 `assets` 子目录、标签和语言 `lang` 公共文件夹的子目录 .

## 结果模板

根据Coveo平台返回的内容类型对不同类型的结果模板进行渲染,在构建Coveo搜索页面时非常常见.

为 HTML 项目创建结果模板的方法 [核心原子库](https://docs.coveo.com/en/atomic/latest/usage/displaying-results/#defining-a-result-template) 涉及定义一个或多个 `atomic-result-template` 组件,以 HTML 属性配置,在每项结果的属性和元数据上添加条件.

结合 [`<template>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template) HTML标记,这在纯HTML项目中效果非常好.

然而,在使用JSX的React项目中使用,这可能是限制和尴尬的.

对于每一种搜索界面元素,Antomic React都暴露出一个包装: `AtomicResultList`, (中文(简体) ), `AtomicFoldedResultList`,或 `AtomicSearchBoxInstantResults`。这些包装需要 `template` 与联合来文X相结合,可以更直接地使用的财产.

这个 `template` 属性接受带有以下两个函数的函数: `Result` 参数 `AtomicResultList` 财务报告和审定财务报表 `AtomicSearchBoxInstantResults` 包装,或 `FoldedResult` 参数 `AtomicFoldedResultList` 包装 利用这些参数有条件地根据结果项目中可用的属性和字段制作不同的模板.

这个 `template` 函数必须简单地返回有效的 JSX 元素.

以下是一个虚构的搜索页面的例子,该页面定义了YouTube视频的一些预先制作的模板,以及 Salesforce 案例:

```tsx
import {
  Result,
  AtomicResultSectionVisual,
  AtomicResultImage,
  AtomicResultSectionTitle,
  AtomicResultLink,
  AtomicResultSectionBottomMetadata,
  AtomicText,
  AtomicResultNumber,
  AtomicFormatUnit,
  AtomicResultSectionExcerpt,
  AtomicResultText,
  AtomicResultSectionEmphasized,
  AtomicSearchInterface,
  AtomicResultList,
  buildSearchEngine,
  getSampleSearchEngineConfiguration,
} from '@coveo/atomic-react';
import {useMemo} from 'react';

const MyResultTemplateForYouTubeVideos: React.FC<{result: Result}> = ({result}) => {
  return (
    <>
      <AtomicResultSectionVisual>
        <AtomicResultImage field="ytthumbnailurl" />
      </AtomicResultSectionVisual>
      <AtomicResultSectionTitle>
        <AtomicResultLink />
      </AtomicResultSectionTitle>
      {result.raw.ytvideoduration !== undefined && (
        <AtomicResultSectionBottomMetadata>
          <AtomicText value="Duration" />
          <AtomicResultNumber field="ytvideoduration">
            <AtomicFormatUnit unit="minute" />
          </AtomicResultNumber>
        </AtomicResultSectionBottomMetadata>
      )}
    </>
  );
};

const MyResultTemplateForSalesforceCases: React.FC<{result: Result}> = ({result}) => {
  return (
    <>
      <AtomicResultSectionTitle>
        <AtomicResultLink />
      </AtomicResultSectionTitle>
      <AtomicResultSectionExcerpt>
        <AtomicResultText field="excerpt" />
      </AtomicResultSectionExcerpt>
      <AtomicResultSectionEmphasized>
        {result.raw.sfpriority !== undefined && (
          <>
            <AtomicText value="Priority" />
            <AtomicResultText field="sfpriority" />
          </>
        )}
        {result.raw.sfstatus !== undefined && (
          <>
            <AtomicText value="Status" />
            <AtomicResultText field="sfstatus" />
          </>
        )}
      </AtomicResultSectionEmphasized>
    </>
  );
};

const MyDefaultTemplate: React.FC<{}> = () => {
  return (
    <>
      <AtomicResultSectionTitle>
        <AtomicResultLink />
      </AtomicResultSectionTitle>
      <AtomicResultSectionExcerpt>
        <AtomicResultText field="excerpt" />
      </AtomicResultSectionExcerpt>
    </>
  );
};

const MyResultTemplateFunction = (result: Result) => {
  if (result.raw.filetype === 'YoutubeVideo') {
    return <MyResultTemplateForYouTubeVideos result={result} />;
  }

  if (result.raw.objecttype === 'Case') {
    return <MyResultTemplateForSalesforceCases result={result} />;
  }

  return <MyDefaultTemplate />;
};

const MyPage = () => {
  const engine = useMemo(
    () =>
      buildSearchEngine({
        configuration: getSampleSearchEngineConfiguration(),
      }),
    []
  );

  return (
    <AtomicSearchInterface engine={engine}>
      <AtomicResultList template={MyResultTemplateFunction} />
    </AtomicSearchInterface>
  );
};
```

## 样式结果模板组件

由于原子网络组件的使用方式 [阴影多姆](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_shadow_DOM) 财务报告和审定财务报表 [中央支助部分](https://developer.mozilla.org/en-US/docs/Web/CSS/::part) 要提供封装,在任何结果模板中要样式元素时,必须遵循这些准则.

### 备选办法1 -- -- 使用高阶组件(HOC)

如果您不需要创建任何 CSS 规则, 以原子结果组件的阴影部分为目标, 此选项将运作良好 .

例如,如果您想要修改模板中所有结果链接的颜色以 `pink`你可以这样

```tsx
import {AtomicResultLink, AtomicSearchInterface, AtomicResultList} from '@coveo/atomic-react';
import {buildSearchEngine, getSampleSearchEngineConfiguration} from '@coveo/headless';
import {useMemo} from 'react';

const MyStyledResultLink: React.FC<React.ComponentProps<typeof AtomicResultLink>> = (props) => {
  return (
    <AtomicResultLink {...props} style={{color: 'pink'}}>
      {props.children}
    </AtomicResultLink>
  );
};

const MyPage = () => {
  const engine = useMemo(
    () =>
      buildSearchEngine({
        configuration: getSampleSearchEngineConfiguration(),
      }),
    []
  );

  return (
    <AtomicSearchInterface engine={engine}>
      <AtomicResultList
        template={(result) => {
          return <MyStyledResultLink />;
        }}
      />
    </AtomicSearchInterface>
  );
};
```

这个方法可以让您将任何核心原子组件包在一个有样式的组件内,然后可以在一个或多个模板中重新使用. 如本文所示,可以采用内置式,也可以采用使用CSS模块等更先进的技术.

使用 `React.ComponentProps<typeof AnyAtomicComponent>` 允许您提取核心组件所暴露出的任何道具,并在需要时加以增强.

### 选项2 - 使用样式标签

此选项在所有情景中都有效,并允许您以类似使用平面 HTML 的方式瞄准原子结果组件暴露出的任何"阴影"部分.

以下是一个实例,它使一个文本成为: `AtomicResultBadge` 粉红色 :

```tsx
import {AtomicSearchInterface, AtomicResultList, AtomicResultBadge} from '@coveo/atomic-react';
import {buildSearchEngine, getSampleSearchEngineConfiguration} from '@coveo/headless';
import {useMemo} from 'react';

const myStyles = `
atomic-result-badge::part(result-badge-element) {
    color: pink;
}
`;

const MyPage = () => {
  const engine = useMemo(
    () =>
      buildSearchEngine({
        configuration: getSampleSearchEngineConfiguration(),
      }),
    []
  );

  return (
    <AtomicSearchInterface engine={engine}>
      <AtomicResultList
        template={(result) => (
          <>
            <style>{myStyles}</style>
            <AtomicResultBadge />
          </>
        )}
      />
    </AtomicSearchInterface>
  );
};
```

## 本地化(i18n)

原子反应搜索接口组件显示可选 `localization` 选项,这需要调用功能,让您处理 [本地化](https://docs.coveo.com/en/atomic/latest/usage/atomic-localization/)。 。 。 .

```tsx
import {AtomicSearchInterface} from '@coveo/atomic-react';

<AtomicSearchInterface
  localization={(i18n) => {
    i18n.addResourceBundle('en', 'translation', {
      search: "I'm feeling lucky!",
    });
  }}
></AtomicSearchInterface>;
```

## 使用CDN脚本( IIFE)

对于这种方法的工作,您需要按正确的顺序在页面中拉出不同的脚本,使用适当的外部依赖性与匹配的版本.

第一,确定所需版本 `@coveo/atomic`, (中文(简体) ), `@coveo/headless`, (中文(简体) ), `react` 财务报告和审定财务报表 `react-dom` 用于 `@coveo-atomic-react`。 。 。 .

你可以跑来跑去 `npm view @coveo/atomic-react@latest version dependencies devDependencies peerDependencies`,像这样:

```
$ npm view @coveo/atomic-react@latest version dependencies devDependencies peerDependencies

version = '2.1.35'
dependencies = { '@coveo/atomic': '2.19.16' }
devDependencies = {
  '@coveo/headless': '2.8.10',
  '@rollup/plugin-commonjs': '^22.0.2',
  '@rollup/plugin-node-resolve': '^14.1.0',
  '@rollup/plugin-replace': '^4.0.0',
  '@rollup/plugin-typescript': '^8.5.0',
  '@types/node': '15.14.9',
  '@types/react': '18.0.17',
  '@types/react-dom': '18.0.6',
  ncp: '2.0.0',
  react: '18.2.0',
  'react-dom': '18.2.0',
  rollup: '^2.79.0',
  'rollup-plugin-polyfill-node': '^0.10.2',
  'rollup-plugin-terser': '^7.0.2'
}
peerDependencies = {
  '@coveo/headless': '^2.0.0',
  react: '>=18.0.0',
  'react-dom': '>=18.0.0'
}
```

在上述例子中,你可以看到,截至本报告撰写之时:

-   当前最新版本 `@coveo/atomic-react` 实值 `2.1.35`。 。 。 .
-   当前的最新版本正在使用 `@coveo/atomic` 版本时 `2.19.16`。 。 。 .
-   当前的最新版本正在使用 `@coveo/headless` 版本时 `2.8.10`。 。 。 .
-   当前的最新版本正在使用 `react`编号 :`react-dom` 载于第18版及以上.

然后,我们需要在我们的页面中增加必要的依赖。 你可以这么做:

```html
<head>
  <!-- React, ReactDOM and ReactDOMServer need to be included  -->
  <script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
  <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
  <script
    crossorigin
    src="https://unpkg.com/react-dom@18/umd/react-dom-server-legacy.browser.production.min.js"
  ></script>

  <!-- Optional script, which allows to use JSX directly in an inline script in the page -->
  <script crossorigin src="https://unpkg.com/@babel/standalone@7/babel.min.js"></script>

  <!-- @coveo/headless need to be included as a dependency -->
  <!-- Note the matching major and minor version as explained above -->
  <script crossorigin src="https://static.cloud.coveo.com/headless/v2.8/headless.js"></script>

  <!-- @coveo/atomic need to be included as a dependency -->
  <!-- Note the matching major and minor version as explained above -->
  <script
    crossorigin
    type="module"
    src="https://static.cloud.coveo.com/atomic/v2.19/atomic.esm.js"
  ></script>

  <!--And then finally @coveo/atomic-react is included -->
  <!-- Note the matching major and minor version as explained above -->
  <script
    crossorigin
    src="https://static.cloud.coveo.com/atomic-react/v2.1/iife/atomic-react.min.js"
  ></script>
</head>
```

完成后,您可以开始使用 `CoveoAtomicReact` 直接使用内嵌脚本标签 :

```html
<!doctype html>
<html>
  <head>
    [...]
  </head>
  <body>
    <div id="container"></div>
  </body>
  <script type="text/babel">
    'use strict';

    const {buildSearchEngine} = CoveoHeadless;

    const {
      buildSearchEngine,
      AtomicSearchInterface,
      AtomicSearchBox,
      AtomicResultList
    } = CoveoAtomicReact;

    class SearchPage extends React.Component {
      constructor(props) {
        super(props);
        // Configure engine
        this.engine = buildSearchEngine({...});
      }

      render() {
        return (
          <AtomicSearchInterface engine={this.engine}>
            <AtomicSearchBox />
            <AtomicResultList
              template={MyTemplateFunction}
            />
            [... etc ...]
          </AtomicSearchInterface>
        );
      }
    }

    const domContainer = document.querySelector('#container');
    ReactDOM.createRoot(domContainer).render(<SearchPage />);
  </script>
</html>
```

## 常见问题

### @coveo/atomic-react 是什么？

为原子元件库执行特定包装

### 如何安装 @coveo/atomic-react？

在项目目录运行 npm install @coveo/atomic-react，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：react（^18 \|\| ^19）、react-dom（^18 \|\| ^19）、@coveo/headless（^3\.58\.1）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @coveo/atomic-react 支持 TypeScript 吗？

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

### @coveo/atomic-react 支持 ESM 还是 CommonJS？

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

### @coveo/atomic-react 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js ^20\.9\.0 \|\| ^22\.11\.0 \|\| ^24\.11\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @coveo/atomic-react 可以商用吗？

@coveo/atomic-react 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @coveo/atomic-react 的下载量有多少？

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

### @coveo/atomic-react 还在维护吗？

最新版本 3\.11\.51 发布于 2026/11/09（1 天前）；至今共发布 4434 个版本，其中过去 12 个月发布了 64 个；首次发布于 2022/01/10。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

