【问题标题】:Can StencilJS component use external theming?StencilJS 组件可以使用外部主题吗?
【发布时间】:2018-10-06 08:25:36
【问题描述】:

我正在尝试使用 StencilJS 为我正在处理的多个项目创建可重用的 Web 组件。 但是我很难将主要应用程序的颜色主题继承到我的 Stencil 按钮组件。 示例:我想为我的应用程序使用不同的主要和次要颜色,这些应用程序适用于我的 Stencil 组件,例如原色按钮。但我该如何做到这一点?我正在使用 sass 样式,并使用我的主题在我的 Stencil 项目中本地设置主变量。但是编译后不知道怎么导入外部sass/css文件。

<my-button color="primary">This is a primary button</my-button>

【问题讨论】:

    标签: sass web-component stenciljs


    【解决方案1】:

    一个选项是在定义组件时关闭 Shadow DOM。这将允许您的 Web 组件从正在使用该组件的应用程序继承 CSS。

    @Component({
      tag: 'shadow-component',
      styleUrl: 'shadow-component.css',
      shadow: false
    })
    

    【讨论】:

      【解决方案2】:

      Styling 文档的底部有一节介绍如何使用 CSS 变量:

      在本例中,我们定义了一个名为 --app-primary-color 的 CSS 变量,其颜色设置为 #488aff。此示例中的 :root 选择器是一个 CSS 伪选择器,它在项目的根元素(通常为 &lt;html&gt;)上定义变量,以便可以在您的应用中使用该变量。

      所以如果你有一个这样的按钮组件:

      @Component({ tag: 'my-button', styleUrl: 'button.css' })
      export class Button {
        render() {
          return <div class="button"><slot /></div>;
        }
      }
      

      下面是button.css

      .button {
        background: var(--primary-color, tomato);
        color: var(--light-color, white);
      
        display: block;
        padding: 1em 2em;
        border-radius: 0.2em;
        font-family: sans-serif;
        text-align: center;
        text-transform: uppercase;
      }
      

      然后,您可以通过在 CSS 中的某处设置变量来覆盖所有按钮颜色:

      :root {
        --primary-color: mediumseagreen;
      }
      

      CSS 变量也可以使用 Javascript 设置,它们甚至可以由 Stencil 为旧版浏览器填充。

      JSFiddle 示例:http://jsfiddle.net/5fv9r6e1/


      顺便说一句,在你的组件装饰器中你也可以设置shadow: true 来启用Shadow DOM,然后你可以使用:host 选择器并且在这个例子中不需要包装div:

      @Component({ tag: 'my-button', styleUrl: 'button.css', shadow: true })
      export class Button {
        render() {
          return <slot />;
        }
      }
      

      css:

      :host {
        background: var(--primary-color, tomato);
        color: var(--light-color, white);
      
        display: block;
        padding: 1em 2em;
        border-radius: 0.2em;
        font-family: sans-serif;
        text-align: center;
        text-transform: uppercase;
      }
      

      Ionic 4 经常使用这个概念,因此可能值得看看他们的 Stencil 组件:https://github.com/ionic-team/ionic/tree/master/core/src/components

      【讨论】:

        猜你喜欢
        • 2017-03-15
        • 2016-10-23
        • 2019-08-14
        • 2022-07-21
        • 2020-11-14
        • 1970-01-01
        • 1970-01-01
        • 2018-05-13
        • 1970-01-01
        相关资源
        最近更新 更多