首页 > 解决方案 > litElement 在静态样式中使用类变量

问题描述

我需要在我的 litElement 类中计算相同的弹出框位置。接下来将其用作样式值。例如。:

export const defaultProps = {
  wrapperTop: 0,
}

export class Popover extends ScopedElementsMixin(LitElement) {

  ...
  static get properties() {
    return {
      wrapperTop: { type: String || Number, reflect: true},
    }
  }

  ...

 constructor() {
   super();

   this.wrapperTop = this.defaultProps.wrapperTop
 }

static get styles() {
  return css`
  .popover-wrapper {
     top: ${this.wrapperTop} //this.wrapperTop is undefined
   }`
 }

 calculateY () {
  //calculate Y depend on some element position
 }

 update() {
  calculateY()
 }

 ...
 
 return html`<div class="popoverWrapper"> ... </div>`
}

而且我找不到使用 this.wrapperTop 获取静态样式的方法。它是未定义的。有一些方法可以做到这一点,或者我必须在渲染中使用 style=""?

标签: styleslit-element

解决方案


添加unsafeCSS到您的导入:

import { html, css, LitElement, unsafeCSS } from 'lit-element';

使用

static get styles() {
  return css`
  .popover-wrapper {
     top: ${unsafeCSS(this.wrapperTop)} //this.wrapperTop is undefined
   }`
}

推荐阅读