Skip to content

Register Element

The first step of a custom element is: registering the element.

After successful registration, it can be imported and exported as JSON.

Notes

In a TypeScript environment, you need to enable decorator support in the tsconfig.json configuration file:

json
{
  "compilerOptions": {
    "experimentalDecorators": true // Enable decorator support
  }
}

To build cross-platform elements, you need to import @leafer-ui/core (cross-platform core package, used to replace the leafer-ui package) and @leafer-ui/interface (interfaces) as external dependencies.

ts
import { Rect } from '@leafer-ui/core'

export class CustomRect extends Rect {}

Registration Steps

1. Register Element

Register the element via the registerUI() method.

Implementation principle: store the element class using its tag property as the key.

2. Define Tag Name

Define a globally unique tag name.

When importing JSON, the corresponding element class is located via the tag property and instantiated.

Example

ts
// #自定义元素 [注册元素]
import { Rect, registerUI } from '@leafer-ui/core' // 引入跨平台核心包


@registerUI()  // 1. 注册元素
class Custom extends Rect {

    public get __tag() { return 'Custom' } // 2. 定义全局唯一的 tag 名称

}



// 使用自定义元素
import { Leafer, UI } from 'leafer-ui'

const leafer = new Leafer({ view: window })
const custom = new Custom({ width: 100, height: 200, fill: 'blue', draggable: true })

leafer.add(custom)

const json = custom.toJSON()
console.log(json) // 导出json {tag: 'Custom', width: 200, height: 50, fill: 'blue', draggable: true }

json.y = 300
leafer.add(UI.one(json)) // 通过json创建自定义元素
js
import { Rect } from '@leafer-ui/core' // 引入跨平台核心包


class Custom extends Rect {

    get __tag() { return 'Custom' } // 2. 定义全局唯一的 tag 名称

}

Custom.registerUI() // 1. 注册元素


// 使用自定义元素
import { Leafer, UI  } from 'leafer-ui'

const leafer = new Leafer({ view: window })
const custom = new Custom({ width: 100, height: 200, fill:'blue', draggable: true })

leafer.add(custom)

const json = custom.toJSON()
console.log(json) // 导出json {tag: 'Custom', width: 200, height: 50, fill: 'blue', draggable: true }

json.y = 300
leafer.add(UI.one(json)) // 通过json创建自定义元素

Next Step

Register Data

Released under the MIT License.