元素实用程序

typescript
interface ElementOptions<A> {
    attributes?: A
    textContent?: string
    htmlContent?: string
    childNodes?: Node[]
    ns?: 'http://www.w3.org/1999/xhtml' | 'http://www.w3.org/2000/svg'
}

type element = <A>(tagName: string, options?: ElementOptions<A>) => Element

element 属性只是一个函数,允许您在一次调用中创建 DOM 元素。

通常,在使用 DOM 元素时,我们会创建并将它们拼凑在一起。

javascript
const button = document.createElement('button')
button.type = 'button'
button.textContent = 'click me'

button.addEventListener('click', () => {
    console.log('clicked')
})

创建一个简单的按钮需要很多步骤。使用 element 也是如此:

javascript
const button = element('button', {
    textContent: 'click me',
    attributes: {
        type: 'button',
        onclick: () => {
            console.log('clicked')
        },
    },
})

element 在后台使用 addEventListener,并通过轻松检测 Web 组件元素来为您处理非原始值。

childNodes 和 htmlContent

childNodeshtmlContent 选项允许您根据您想要的处理方式轻松组件更复杂的元素。

以下是使用 childNodes 选项的示例:

javascript
element('ul', {
    attributes: { id: 'items-list' },
    childNodes: [
        element('li', {
            attributes: { class: 'list-item' },
            textContent: 'item 1',
        }),
        element('li', {
            attributes: { class: 'list-item' },
            textContent: 'item 2',
        }),
        element('li', {
            attributes: { class: 'list-item' },
            textContent: 'item 3',
        }),
    ],
})

现在是使用 htmlContent 选项的相同示例:

javascript
element('ul', {
    attributes: { id: 'items-list' },
    htmlContent:
        '<li class="list-item">item 1</li>' +
        '<li class="list-item">item 2</li>' +
        '<li class="list-item">item 3</li>',
})

这里的主要区别在于,使用 childNodes 可以为属性指定函数和属性值,而 htmlContent 仅采用您想要使用的静态 HTML。

网络组件

使用 element 的最佳部分是使用 Web 组件。它将处理所有非原始 props 以确保 Web 组件按其应有的方式获取数据。

javascript
const item = element('todo-item', {
    attributes: {
        data: {
            id: crypto.randomUUID(),
            name: 'buy groceries',
            status: 'pending',
            dateCreated: new Date(),
        },
    },
})

SVG 元素

要创建 SVG 元素,您可以指定 ns 选项及其值 http://www.w3.org/2000/svg,这将为您提供任何 SVG 元素。

javascript
const rect = element('rect', {
    ns: 'http://www.w3.org/2000/svg',
    attributes: {
        x: 10,
        y: 10,
        width: 100,
        height: 100,
    },
})
编辑本文档