> For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/api/lynx-native-api/lynx-view/lynx-view.md.

# `<lynx-view>`

`<lynx-view>` 是一个加载并展示 Lynx 模板的容器组件，可以在 Web 应用中使用它来渲染 Lynx 模板。

## API 参考

完成上述集成后，你可以通过 Lynx for Web 提供的 API 实现更灵活的交互控制，以下是核心 API 的详细说明：

### lynx-view

#### Attributes

| 名称             | 是否必传 | 说明                                                                                |
| :------------- | :--- | :-------------------------------------------------------------------------------- |
| url            | 是    | Rspeedy 产物的url（其它 chunk 的 url 会编译时注入产物自动启动）                                       |
| globalProps    | 否    | 卡片初始化时的 [GlobalProps](/zh/api/lynx-api/lynx/lynx-global-props.md)                 |
| initData       | 否    | 卡片初始化时的 InitData                                                                  |
| browser-config | 否    | 允许在实例级别动态配置 `systemInfo`，如设置 `pixelRatio`，`pixelWidth` 和 `pixelHeight`。           |
| transform-vw   | 否    | 开启 `vw` 转换，允许在容器级别使用 CSS 自定义属性代替 `vw` 单位，例如 `1vw` 转换为 `calc(1 * var(--vw-unit))`。 |
| transform-vh   | 否    | 开启 `vh` 转换，允许在容器级别使用 CSS 自定义属性代替 `vh` 单位，例如 `1vh` 转换为 `calc(1 * var(--vh-unit))`。 |

#### Properties

##### nativeModulesMap

自定义的 [NativeModule](/zh/guide/use-native-modules.md)，key 为 module 名称，value 为 module 实现（一个 esm url）：

```ts
type NativeModulesMap = Record<string, string>;
```

示例:

```ts
const nativeModulesMap = {
  CustomModule: URL.createObjectURL(
    new Blob(
      [
        `export default function(NativeModules, NativeModulesCall) {
    return {
      async getColor(data, callback) {
        const color = await NativeModulesCall('getColor', data);
        callback(color);
      },
    }
  };`,
      ],
      { type: 'text/javascript' },
    ),
  ),
};
lynxView.nativeModulesMap = nativeModulesMap;
```

##### onNativeModulesCall

处理 NativeModules（JSB 等）相关调用的入口:

```ts
(name: string, data: any, moduleName: string) => Promise<any> | any;
```

示例：

```ts
// 处理 NativeModule.bridge.call('request')
lynxView.onNativeModulesCall = (name, data, moduleName) => {
  if (moduleName === 'bridge') {
    if (name === 'request') {
      // ...

      // return data 会被自动处理为 callback data
      return {};
    }
  }
};
```

##### browserConfig

支持在实例级别动态配置 `systemInfo`，通过 `browserConfig` 属性进行设置：

```ts
lynxView.browserConfig = {
  pixelRatio: 2,
  pixelWidth: 375,
  pixelHeight: 812,
};
```

#### Events

##### error

报错信息通知：

```ts
type LynxError = CustomEvent<{
  error: Error;
  sourceMap: {
    offset: {
      // 行偏移量
      line: number;
      // 列偏移量
      col: number;
    };
  };
  release: string;
  fileName: 'lepus.js' | 'app-service.js';
}>;

lynxView.addEventListener('error', (err: LynxError) => {
  // ...
});
```

#### Methods

##### updateData

[详见](/zh/api/lynx-native-api/lynx-view/update-meta-data.md)

```ts
export type Cloneable<T = string | number | null | boolean | undefined> =
  | T
  | Record<string, T>
  | T[];

updateData(
  data: Cloneable,
  updateDataType: UpdateDataType,
  callback?: () => void,
): void
```

##### updateGlobalProps

[详见](/zh/api/lynx-api/main-thread/lynx-global-props.md)

```ts
updateGlobalProps(data: Cloneable): void;
```

##### sendGlobalEvent

[详见](/zh/api/lynx-native-api/lynx-view/send-global-event.md)

```ts
sendGlobalEvent(eventName: string, params: Cloneable[]): void;
```

#### 宽、高

:::note
lynx-view的内部排版会被强制移出外部排版流
:::

我们会给所有 lynx-view 强制应用 [CSS Containment](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_containment)。

也就是默认情况下，您需要给 lynx-view 设置一个宽高。宽高可以是 `flex-grow` 分配的、可以是百分比指定的，但是不可以是“撑开”的。设置宽高是强烈推荐的做法，也是性能的最佳实践。

有些情况下您的确需要由 lynx-view 的内容决定宽或高，您可以设置 `height="auto"` 或者 `width="auto"` 来启动自动宽高监听器。在这种情况下，lynx-view 的内部排版依旧与外部排版流独立。

### FAQ

#### 运行时报错：`Uncaught SecurityError: Failed to construct 'Worker': Script at 'xxx' cannot be accessed from origin 'xxx'`.

这是因为 Worker 加载远程脚本需要遵守[同源策略](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy)，而项目的 JS 资源一般会部署在 CDN 上，从而造成了跨域问题。

可以通过引入 [remote-web-worker](https://github.com/jantimon/remote-web-worker) 的形式解决：

```ts
// 引入位置需要保证在 @lynx-js/web-core 前
import 'remote-web-worker';

import '@lynx-js/web-core/client';
document.body.innerHTML = `
<lynx-view
    style="height:100vh; width:100vw;"
    url="http://localhost:3000/main/index.main.bundle"
>
</lynx-view>`;
```

#### 性能优化

我们提供了 RSBuild 插件来做性能优化，你可以在你的 web 工程中引入[该插件](https://www.npmjs.com/package/@lynx-js/web-platform-rsbuild-plugin)

## 从旧版本迁移

如果您正在升级到 `@lynx-js/web-core@0.20.0`，请注意由于架构升级，这里存在重大的破坏性变更。

### 初始化变更

您不再需要手动导入 CSS，也不再需要 `@lynx-js/web-elements`。初始化过程得到了简化：

```ts
// 升级前:
import '@lynx-js/web-core/client';

// 升级后:
import '@lynx-js/web-core/client';
```

### API 变更

移除了以下 `<lynx-view>` 属性，不再被支持：

- `thread-strategy`
- `customTemplateLoader`
- `overrideLynxTagToHTMLTagMap`
- `inject-head-links`
