【问题标题】:StencilJS Component StylesStencilJS 组件样式
【发布时间】:2017-10-09 04:46:40
【问题描述】:

使用ComponentDecoratorstyles 选项/属性的正确方法是什么?将styles 属性与来自存储库stencil-component-starter 的默认my-name 组件一起使用似乎不会影响相应组件的样式,也不会在<head> 中生成类似<style> 标记的东西。 styles 打算如何工作?还是尚未实施?如果目标是避免需要加载单独的 CSS 资源,但为组件提供样式,styles 是正确的选择,还是需要使用其他属性,例如 host

下面是从 stencil-component-starter]1 生成的示例组件,其中 stylesUrl @Component 属性替换为 styles 属性并设置 font-size 属性。在devbuild 任务期间不会产生错误。

import { Component, Prop } from '@stencil/core';

@Component({
  tag: 'my-name',
  styles: `my-name { font-size: 24px; }`
})
export class MyName {

  @Prop() first: string;

  render() {
    return (
      <div>
        Hello, my name is {this.first}
      </div>
    );
  }
}

ComponentDecorator 定义为:

export interface ComponentOptions {
    tag: string;
    styleUrl?: string;
    styleUrls?: string[] | ModeStyles;
    styles?: string;
    shadow?: boolean;
    host?: HostMeta;
    assetsDir?: string;
    assetsDirs?: string[];
}

感谢您提供的任何帮助!

【问题讨论】:

    标签: web-component stenciljs


    【解决方案1】:

    我刚刚尝试了最新的版本 0.0.6-22,现在它似乎完全可以工作了。

    在编译的时候,它会告诉你你的样式内容是否有效(主要是寻找有效的选择器)。

    这是一个工作示例(带有一个简单的字符串):

    import { Component, Prop } from "@stencil/core";
    
    @Component({
      tag: "inline-css-example",
      styles: 'inline-css-example { font-size: 24px; }'
    })
    export class InlineCSSExampleComponent {
      @Prop() first: string;
    
      render() {
        return <div>Hello, my name is {this.first}</div>;
      }
    }
    

    这个也可以,使用 ES6 模板字符串(只显示多行):

    import { Component, Prop } from "@stencil/core";
    
    @Component({
      tag: "inline-templatestring-css-example",
      styles: `
        inline-templatestring-css-example {
          font-size: 24px;
        }
      `
    })
    export class InlineCSSExampleComponent {
      @Prop() first: string;
    
      render() {
        return <div>Hello, my name is {this.first}</div>;
      }
    }
    

    (已编辑以显示自 0.0.6-13 以来的演变)

    【讨论】:

    • 谢谢!奇怪的是styles 只能与styleUrl 一起使用。我的目标是避免生成的资产生成和引用 CSS 文件。也许这会在未来得到改进,style 内容将以某种方式与构建资产的 JS 捆绑在一起。
    • 嘿@AlexanderStaroselsky 你说的“只有连词...”是什么意思?你需要两者吗因为这个答案中的样本只有styles
    • @MatthiasMax 最初的目标是使用 styles 属性注入样式的方式来避免需要单独的样式表。自问答时间以来,对 StencilJS 进行了许多重要更新,包括注入样式。这不再是问题,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-21
    • 1970-01-01
    • 2021-01-30
    • 1970-01-01
    • 2020-05-03
    • 2020-01-08
    相关资源
    最近更新 更多