사용자 지정 컴포넌트

Web SDK는 사용자 지정 컴포넌트를 통합하는 여러 방법을 제공하므로 기능을 확장하고 원하는 대로 조정할 수 있습니다. 이 가이드에서는 자주 사용하는 몇 가지 방법을 소개합니다.

Univer는 렌더링 호출에 인수로 구성 요소를 허용하지 않습니다. 구성 요소는 Facade API를 통해 등록해야합니다. Univer 마운트를 참조 할 수 있습니다.

Facade API 인스턴스가 아직 사용할 수없는 경우 Facade API를 참조하십시오.

사용자 지정 컴포넌트 등록

TypeScript
univerAPI.registerComponent(componentKey, CustomComponent, options)

univerAPI.registerComponent는 구성 요소를 등록하고 세 가지 인수를 취합니다.

  • componentKey : Univer 내부를 참조하는 데 사용되는 구성 요소의 고유 식별자.
  • CustomComponent : React 구성 요소, Vue 부품 또는 웹 구성 요소가 될 수있는 구성 요소 자체.
  • options: 기구와 같은 선택적인 조정은 성분에 또는 다른 관련 윤곽 달려 있습니다.

React 컴포넌트

React 구성 요소는 추가 구성이 필요하지 않습니다. 구성 요소는 다음과 같은 예에서 유효한 React 부품이어야합니다.

TSX
function ReactComponent(props: Record<string, any>) {  return <div>Hello Univer!</div>}univerAPI.registerComponent('MyReactComponent', ReactComponent)

Vue 컴포넌트

Vue 3.x

Vue 구성 요소의 경우 @univerjs/ui-adapter-vue3 패키지를 설치하고 UniverVue3AdapterPlugin를 등록하십시오.

Shell
pnpm add @univerjs/ui-adapter-vue3
TypeScript
import { UniverVue3AdapterPlugin } from '@univerjs/ui-adapter-vue3'univer.registerPlugin(UniverVue3AdapterPlugin)

framework를 'vue3'로 전달하면 구성품을 등록할 수 있습니다.

TSX
const Vue3Component = defineComponent({  setup(props) {    return () => <div>Hello Univer!</div>  },})univerAPI.registerComponent('MyVue3Component', Vue3Component, {  framework: 'vue3',})

Vue 2.x

Vue 2.x는 end-of-life에 도달하고 더 이상 유지되지 않습니다, 그래서 Univer는 현재 그것에 대한 UI 어댑터 플러그인을 제공하지 않습니다. 어댑터는 사용자 정의 플러그인으로 구현 될 수 있습니다. 아래 코드는 시작점으로 봉사 할 수있는 Vue 2x 어댑터 플러그인입니다.

TypeScript
import { DependentOn, Inject, Injector, Plugin } from '@univerjs/core'import { ComponentManager, UniverUIPlugin } from '@univerjs/ui'import Vue from 'vue'/** * The plugin that allows Univer to use Vue 2 components as UI components. */@DependentOn(UniverUIPlugin)export class UniverVue2AdapterPlugin extends Plugin {  static override pluginName = 'UNIVER_UI_VUE2_ADAPTER_PLUGIN'  constructor(    private readonly _config = {},    @Inject(Injector) protected readonly _injector: Injector,    @Inject(ComponentManager) protected readonly _componentManager: ComponentManager,  ) {    super()  }  override onStarting(): void {    const { createElement, useEffect, useRef } = this._componentManager.reactUtils    this._componentManager.setHandler('vue2', (component: any) => {      return (props: Record<string, any>) =>        createElement(VueComponentWrapper, {          component,          props: Object.keys(props).reduce<Record<string, any>>((acc, key) => {            if (key !== 'key') {              acc[key] = props[key]            }            return acc          }, {}),          reactUtils: { createElement, useEffect, useRef },        })    })  }}export function VueComponentWrapper(options: {  component: any  props: Record<string, any>  reactUtils: typeof ComponentManager.prototype.reactUtils}) {  const { component, props, reactUtils } = options  const { createElement, useEffect, useRef } = reactUtils  const domRef = useRef<HTMLDivElement>(null)  useEffect(() => {    if (!domRef.current) return    const Constructor = Vue.extend(component)    const instance = new Constructor({      data: props,    })    instance.$mount()    domRef.current.appendChild(instance.$el)    return () => {      instance.$destroy()    }  }, [props])  return createElement('div', { ref: domRef })}

그런 다음 플러그인을 등록:

TypeScript
import { UniverVue2AdapterPlugin } from './ui-adapter-vue2'univer.registerPlugin(UniverUIPlugin)univer.registerPlugin(UniverVue2AdapterPlugin)

Vue 2.x 성분은 framework 세트를 'vue2'에 필요로 합니다:

TSX
const Vue2Component = Vue.component('MyVue2Component', {  template: '<div>Hello, Univer!</div>',})univerAPI.registerComponent('MyVue2Component', Vue2Component, {  framework: 'vue2',})

Web Components

웹 구성 요소를 등록하려면 구성 요소는 웹 구성 요소 표준을 따르야합니다. @univerjs/ui-adapter-web-component 패키지를 설치하고 UniverWebComponentAdapterPlugin를 등록하십시오.

Shell
pnpm add @univerjs/ui-adapter-web-component
TypeScript
import { UniverWebComponentAdapterPlugin } from '@univerjs/ui-adapter-web-component'univer.registerPlugin(UniverWebComponentAdapterPlugin)

framework를 'web-component'로 전달하십시오:

TSX
class WebComponent extends HTMLElement {  constructor() {    super()    const shadow = this.attachShadow({ mode: 'open' })    const div = document.createElement('div')    div.textContent = 'Hello Univer!'    shadow.appendChild(div)  }}univerAPI.registerComponent('my-web-component', WebComponent, {  framework: 'web-component',})

Angular

@angular/elements의 createCustomElement는 Angular 구성품을 사용자 정의 요소로 변환합니다. 요소가 Univer 웹 구성 요소 어댑터에 등록 된 후 Angular 부품은 Univer 측바 또는 대화 상자에서 나타날 수 있습니다.

@angular/core, @univerjs/ui-adapter-web-component와 같은 버전에서 @angular/elements를 다른 Univer 패키지와 같은 버전으로 추가하십시오.

Univer가 초기화된 후이 함수를 호출합니다. Angular 인젝터는 호스트 구성품에 의해 공급됩니다: private readonly injector = inject(Injector)로 가져와 registerAngularPanel(univer, univerAPI, this.injector)를 호출합니다. 호스트 구성 요소는 inject 및 Injector @angular/core에서 가져옵니다.

TypeScript
import type { Injector } from '@angular/core'import type { FUniver, Univer } from '@univerjs/presets'import { Component } from '@angular/core'import { createCustomElement } from '@angular/elements'import { UniverWebComponentAdapterPlugin } from '@univerjs/ui-adapter-web-component'@Component({  selector: 'app-angular-panel',  standalone: true,  template: '<p>Hello from Angular!</p>',})export class AngularPanelComponent {}export function registerAngularPanel(univer: Univer, univerAPI: FUniver, injector: Injector) {  const element = createCustomElement(AngularPanelComponent, { injector })  univer.registerPlugin(UniverWebComponentAdapterPlugin)  return univerAPI.registerComponent('univer-angular-panel', element, {    framework: 'web-component',  })}

편집기가 렌더링되면, 사이드바 콘텐츠로 등록 된 키를 전달합니다.

TypeScript
const sidebar = univerAPI.openSidebar({  header: { title: 'Angular' },  children: { label: 'univer-angular-panel' },  width: 360,})

등록 핸들과 사이드바 핸들을 유지하고 dispose()를 호출하면 더 이상 필요하지 않습니다. 응용 프로그램에 한 번 요소를 등록하십시오. 그 이름은 하이픈을 포함해야하며 Angular 구성 요소 선택자와 다릅니다.

Angular 요소 맵은 요소 속성에 입력하고 DOM CustomEvent 이벤트에 출력합니다. Univer 어댑터는 속성을 설정하지만 자체에 Angular 출력을 구독하지 않습니다. 응용 프로그램은 필요한 경우 해당 이벤트를 브리지해야합니다.

사용자 지정 컴포넌트 사용

위치 Univer의 사용자 정의 구성 요소 아래 방법, 확장 및 UI를 사용자 정의.

주의

  1. Univer가 렌더링을 완료 한 후이 방법을 호출합니다.
  2. 사용하기 전에 구성 요소를 등록하십시오.
  3. dispose()를 호출하여 추가하고 메모리 누출을 방지합니다.

사용자 지정 메뉴 항목 추가

상단의 리본과 오른쪽 클릭의 Context 메뉴는 호스트 사용자 정의 구성 요소를 모두 할 수 있습니다. 메뉴 항목은 플러그인에 의해 등록되므로 사용자 정의 플러그인을 추가해야합니다. 사용자 정의 메뉴 항목에 대 한 최고의 연습 가이드는 시작점으로 사용할 수 있습니다.

기본 제공 컴포넌트 교체

- 기타

내장 구성 요소를 해결하는 것은 그것에 의존하는 기능을 깰 수 있습니다. 소스 코드와 문서를 읽고 교체를 시도하기 전에, 그리고 주의와 진행.

univerAPI.registerComponent는 기본 (override: true)에 의해 과속을 등록합니다. 과속은 플러그인이 이전 또는 호출 후 기본을 등록하는지 여부에 관계없이 내장 된 구성 요소에 우선 순위를 부여합니다. 하나의 과속은 각 componentKey에 대한 활성이 될 수 있으므로 다른 등록을 등록하기 전에 이전 등록을 해제합니다. 반환된 등록에 dispose()를 호출하면 내장 기본을 복원합니다. 대신 { override: false }로 등록하면 기본 컴포넌트가 등록됩니다.

첫 번째로 열린다. 등록은 이미 장착 된 전망이 렌더링되지 않습니다.

시트는 다음과 같은 키를 공개 패키지 항목에서 내보내기; 일치 내장 구성 요소를 무시하기 위해 그들을 사용합니다 :

컴포넌트공개 키패키지
정의된 이름DEFINED_NAME_CONTAINER@univerjs/sheets-ui
추가 함수MORE_FUNCTIONS_COMPONENT@univerjs/sheets-formula-ui
데이터 유효성 검사DATA_VALIDATION_PANEL@univerjs/sheets-data-validation-ui
조건부 서식CF_PANEL_KEY@univerjs/sheets-conditional-formatting-ui

예를 들어, 다음과 같은 코드는 내장 ColorPicker 구성 요소를 대체합니다.

TSX
// Following code only replaces the UI of the built-in ColorPicker component, not its functionalityuniverAPI.registerComponent('UI_COLOR_PICKER_COMPONENT', () => <input type="color" />)

콘텐츠 컴포넌트로 사용

사이드바에서 사용

univerAPI.openSidebar는 Univer UI 내부의 사이드바를 열고 등록 된 구성 요소를 렌더링합니다.

TSX
// You should register the component at an appropriate time (e.g., after Univer has loaded)univerAPI.registerComponent('MyCustomSidebarComponent', () => <div>Hello Univer!</div>)const sidebar = univerAPI.openSidebar({  header: { title: 'My Sidebar' },  children: { label: 'MyCustomSidebarComponent' },  onClose: () => {    console.log('close')  },  width: 360,})// Later close the sidebarsidebar.dispose()

참조: univerAPI.openSidebar

대화 상자에서 사용

univerAPI.openDialog는 대화 상자를 열고 등록 된 구성 요소를 렌더링합니다.

TSX
// You should register the component at an appropriate time (e.g., after Univer has loaded)univerAPI.registerComponent('MyCustomDialogComponent', () => <div>Hello Univer!</div>)const dialog = univerAPI.openDialog({  id: 'unique-dialog-id', // The unique identifier for the dialog  draggable: true,  width: 300,  title: { title: 'My Dialog' },  children: {    label: 'MyCustomDialogComponent',  },  destroyOnClose: true,  preservePositionOnDestroy: true,  onClose: () => {},})// Later close the dialogdialog.dispose()

참조: univerAPI.openDialog

셀에 팝업 연결

FRange.attachPopup는 특정 셀 범위에 맞춤 팝업을 부착합니다.

  • 팝업은 세포에 붙어있는 임시 DOM 요소입니다. 그것은 보통 일시적인 상태 정보를 표시하고 지속적인 저장을 지원하지 않습니다.
  • 메서드 서명은 FRange.attachPopup(popup: IFCanvasPopup)입니다.
  • 팝업은 세포의 가장자리에 부착하고 그 위치와 방향을 조정합니다.
TSX
// You should register the component at an appropriate time (e.g., after Univer has loaded)univerAPI.registerComponent(  'MyCustomPopupComponent',  () => <div>Hello Univer!</div>,)const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()const fRange = fWorksheet.getRange('A1:J10')// Attach the popup to the first cell of the range// If `disposable` is null, it indicates that the popup was not added successfullyconst disposable = fRange.attachPopup({  componentKey: 'MyCustomPopupComponent',})// Remove the popupdisposable.dispose()

경고 팝업 연결

FRange.attachAlertPopup는 특정 범위의 시작 세포에 경고 팝업을 부착합니다.

TypeScript
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()const fRange = fWorksheet.getRange('A1:B2')const disposable = fRange.attachAlertPopup({  key: 'unique-alert-key', // Unique identifier  title: '这是一个警告!',  message: '这是一个警告!',  width: 300,  height: 200,  // 0: Information  // 1: Warning  // 2: Error  type: 0,})// Remove the alert laterdisposable.dispose()

워크시트에 플로팅 DOM 추가

FWorksheet.addFloatDomToPosition는 작업표에 뜨 DOM 요소를 추가합니다.

  • 이 방법을 사용하기 전에 @univerjs/sheets-drawing-ui 플러그인 또는 @univerjs/preset-sheets-drawing 미리 설치를 설치하십시오.
  • 플로팅 DOM 요소는 작업 시트를 통해 거꾸로하고 지속 가능한 스토리지를 지원합니다.
  • Univer가 렌더링을 완료 한 후이 방법을 호출합니다.
  • componentKey : Univer 내부에 참조하는 데 사용되는 구성 요소의 고유 식별자.
  • 전체 매개변수 정의
TSX
// You should register the component at an appropriate time (e.g., after Univer has loaded)univerAPI.registerComponent(  'MyCustomFloatDOMComponent',  ({ data }) => (    <div>      Hello      {data?.label}      !    </div>  ),)const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()// Add a floating DOM to the worksheet// If `disposable` is null, it indicates that the floating DOM was not added successfullyconst disposable = fWorksheet.addFloatDomToPosition({  componentKey: 'MyCustomFloatDOMComponent',  initPosition: {    startX: 100,    endX: 200,    startY: 100,    endY: 200,  },  // The data for the component  data: {    label: 'Univer',  },})// Remove the floating DOMdisposable.dispose()

이 가이드는 어떠셨나요?

© 2026 DreamNum Co., Ltd.