首页 > 解决方案 > Vaadin Flow:如何将类名添加到模板

问题描述

我在模板文件中有一个 Vaadin 组件:

import {LitElement, html} from 'lit-element';
import '@vaadin/vaadin-text-field/vaadin-text-field.js';
import '@vaadin/vaadin-button/vaadin-button.js';

class HelloWorld extends LitElement {

    render() {
        return html`
            <div>
                <vaadin-text-field id="firstInput"></vaadin-text-field>
                <vaadin-button id="helloButton">Click me!</vaadin-button>
            </div>`;
    }
}

customElements.define('hello-world', HelloWorld);

和服务器端java类文件:

@Tag("hello-world")
@JsModule("./src/hello-world.ts")
public class HelloWorld extends LitTemplate {

    /**
     * Creates the hello world template.
     */
    public HelloWorld() {
        addClassName("my-style"); // Method not available!!
    }
}

在 java 类中,我想为整个模板组件添加一个类名以动态设置它的样式。但是“addClassName()”方法在 LitTemplate 中不可用。是否可以将类名添加到 LitTemplate?在浏览器检查器中,我可以手动将 'class="my-style"' 添加到 hello-world 组件,它可以工作。

标签: vaadinvaadin-flow

解决方案


使用HasStylemixin 访问该方法:

public class HelloWorld extends LitTemplate implements HasStyle { ... }

您可以查看实现以查看下面的内容https://github.com/vaadin/flow/blob/master/flow-server/src/main/java/com/vaadin/flow/component/HasStyle.java


推荐阅读