如何在 Typescript 属性装饰器中访问真正的 HTML 元素

问题描述 投票:0回答:0

想为自己没有Lit的组件库创建一个类似Lit的简单HTML元素属性装饰器

function property({}: { dataPrefixed?: boolean } = { dataPrefixed: false }) {
  return (target: any, propertyName: string) => {
    const descriptor: PropertyDescriptor = {
      set(newVal: string) {
        target.setAttribute(propertyName, newVal)
      },
      get() {
        return target.getAttribute(propertyName)
      },
    }
    Object.defineProperty(target, propertyName, descriptor)
  }
}

// BaseElement extends HTMLElement
class BaseButton extends BaseElement {
  // ...

  @property()
  custom: string

  // ...

  override render() {
    return `
    <${this.custom || 'button'}
      part="button focus">
      ${this.renderContents()}
    </${(this.custom || 'button').split(' ')[0]}>
    `
  }
  renderContents() {
    return html`<slot></slot>`
  }

  // ...
}

但是我得到一个错误

enter image description here

要查看完整代码,请访问GitHub

html typescript decorator web-component native-web-component
© www.soinside.com 2019 - 2024. All rights reserved.