如何在 vaadin 标签上添加 html 格式?

How to add html format on a vaadin label?

我想在 vaadin 标签上添加 html 格式的字符串。该字符串来自数据库并直接进入标签,它必须使用粗体文本、换行符和其他一些花哨的文本内容进行格式化。我找到了几个解决方案,但那些是针对旧版本的 vaadin 的,有什么方法可以在 vaadin 流上执行此操作吗?

您可以使用以下方法将 HTML 内容添加到标签:

        Label label = new Label();
        label.getElement().setProperty("innerHTML","A new line should be created after this <br /> <b>This text is bold</b> <br /> <i> This text is italic</i>");
        add(label);

BUT,如果您只想显示文本,则标签不是可使用的正确元素。如其 API 所述:

Note that Label components are not meant for loose text in the page - they should be coupled with another component by using the setFor(Component) or by adding them to it with the HasComponents.add(Component...) method.

我会改用 HTML 元素 :

        String yourContent ="A new line should be created after this <br /> <b>This text is bold</b> <br /> <i> This text is italic</i>";
        Html html = new Html("<text>" + yourContent + "</text>");
        add(html);

输出:

或者您可以封装功能并创建一个通用组件来显示 HTML 片段,这里使用示例:https://vaadin.com/forum/thread/17072019