【问题标题】:Vaadin Flow: How to add class name to TemplateVaadin Flow:如何将类名添加到模板
【发布时间】:2021-08-17 09:05:38
【问题描述】:

我在模板文件中有一个 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 组件,它可以工作。

【问题讨论】:

    标签: vaadin vaadin-flow


    【解决方案1】:

    使用HasStyle mixin 来访问该方法:

    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 下的内容

    【讨论】:

    • 附带说明:在更高版本的 Vaadin(我目前正在查看版本 20)中,LitTemplate 已经实现了 HasStyle。
    【解决方案2】:

    实现HasStyle 应该可以工作:

    @Tag("hello-world")
    @JsModule("./src/hello-world.ts")
    public class HelloWorld extends LitTemplate implements HasStyle {
        public HelloWorld() {
            addClassName("my-style");
        }
    }
    

    【讨论】:

    • 很抱歉与其他答案同时发布
    猜你喜欢
    • 1970-01-01
    • 2022-01-23
    • 2021-12-04
    • 1970-01-01
    • 2016-07-02
    • 1970-01-01
    • 1970-01-01
    • 2017-10-18
    • 2021-04-09
    相关资源
    最近更新 更多