首页 > 解决方案 > 需要帮助为 Stencil 设置类名

问题描述

因此,在阅读了文档然后在 Stencil 上上了一堂 umedy 课后,我似乎仍然无法在我的对象上设置类名。例如我有以下

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

@Component({
tag: 'my-button',
styleUrl: 'my-button.css'
})

export class MyButton {
@Prop() btext: string;
@Prop() btype: string;

render(){
let classNaming: string = '';
switch(this.btype) {
   case "Primary":
       classNaming += 'My-Button-CSS';
       break;
   case "Secondary"
       classNaming += 'My-Button-CSS';
       break;
}

return <button class={classNaming}>this.btext</button>
}
}
}

问题是课程永远不会出现在按钮上。我知道我在教程中看到的 react-bootstrap 中,但从未使用过 react,它们有 variant="" 这基本上是我想要构建的,并且没有运气让它工作,因为 Stencil 教程和高级项目很少。另一个问题是现有的类都是基于 1.8 的。

标签: stenciljsstencil-component

解决方案


您在第二种情况(情况“次要”)之后忘记了一个冒号(:),并且}在文档的末尾有一个额外的内容。

您可以在webcomponents.dev上使用代码

最终代码应该是:

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

@Component({
  tag: "my-button",
  styleUrl: "my-button.css",
})
export class MyButton {
  @Prop() btext: string;
  @Prop() btype: string;

  render() {
    let classNaming: string = "";
    switch (this.btype) {
      case "Primary":
        classNaming += "My-Button-CSS";
        break;
      case "Secondary":
        classNaming += "My-Button-CSS";
        break;
    }

    return <button class={classNaming}>{this.btext}</button>;
  }
}

推荐阅读