Stenciljs:动态加载styleUrl

时间:2018-09-26 14:59:27

标签: web-component stenciljs

我正在使用stenciljs构建一个Web组件,但我无法基于称为主题的属性加载CSS主题文件。

@Component({
  tag: 'pm-header',
  styleUrl: 'pm-header.scss',
  shadow: true
})

export class PmHeader {

  @Prop() theme: string = 'default';

  ...

  render() {
    return (<nav class={this.theme}></nav>)
  }
}

3 个答案:

答案 0 :(得分:3)

我知道这很晚了,但是希望它能对其他人有所帮助,因为它没有记录在案,我只是花了很多时间来弄清楚。以下代码允许您的自定义组件使用“模式”属性来确定要加载的样式。

步骤1:在组件定义中定义多个styleUrl:

@Component({
    tag: 'my-component',
    styleUrls: {
        default: 'my-component.default.pcss',
        dark: 'my-component.dark.pcss',
    },
})
export class MyComponent { ... }

第2步::创建样式文件(具有共享的通用样式):

  • my-component.common.css

    :host { display: block }
    
  • my-component.default.css

    @import './my-component.common.css';
    :host { color: black }
    
  • my-component.dark.css

    @import './my-component.common.css';
    :host { background: black; color: white }
    

步骤3:更新您的stencil.config.ts以使用globalScript:

export const config: Config = {
    namespace: 'mycomponent',
    globalScript: './src/globals/global.ts',
    ...
}

步骤4:创建全局脚本并定义一个“ setMode”函数,如下所示:

import { setMode } from '@stencil/core';

setMode(elm => {
    return (elm as any).mode || elm.getAttribute('mode') || 'default';
});

第5步:像这样使用您的自定义组件:

<!-- default mode -->
<my-component />
<my-component mode="default" />

<!-- dark mode -->
<my-component mode="dark" />

您可以自定义setMode函数来确定模式-例如,您可以在window上查找设置的属性,或在元素上检查className。由你决定。上面只是一个简单的示例,允许您在元素上使用“模式”属性...如果未指定任何内容,则退回到“默认”。

答案 1 :(得分:0)

在这种情况下,您的组件将始终加载在pm-header.scss中找到的样式。

要基于主题自定义样式,我认为您有两个选择:

1-将所有主题放在pm-header.scss内,并使用Sass保护每个主题:

nav.foo {
  // foo theme goes in here
}

nav.bar {
  // bar theme goes in here
}

2-模板确实提供了styleUrls道具,表面上可以让您在加载时在多个Sass文件之间进行选择。这是Ionic 4所采用的方法(在ios和材料设计之间; here's an example),但是我不认为有关如何实现它的文献很好。您可能必须在Ionic代码中进行挖掘才能走这条路。

答案 2 :(得分:0)

请看下面的例子。即使将阴影设置为true,它也将起作用

@Component({
  tag: 'my-component',
  styleUrls: [
    'my-component.scss'
  ],
  shadow: true
})

export class MyComponent{

  @State() theme: string // when theme changes render needs to be called again

  render () {
      return (
        <div>

          { 
            this.theme &&
            <link rel="stylesheet" href={`path_to_css/${this.theme}.css`} />
          }

          <p>{this.text}</p>
        </div>
      )
    }
}