传递一个布尔值给 Lit 组件。

huangapple go评论60阅读模式
英文:

Pass a boolean value to a Lit Component

问题

我想通过 DOM 将布尔值(true/false)传递给 Lit 组件。
我遇到了问题,因为它总是被转换为 true,我似乎找不到 lit 文档中的一个好例子。

所以基本上是这样的:

<my-element foo="false" />
...
  @property({type: Boolean})
  foo: boolean;

我尝试过的是尝试传递:&quot;${false}&quot;

我创建了一个包含示例的 lit playground 链接

英文:

I want to pass a boolean value (true/false) to a lit component via. the dom.
I'm having issues because it is always converted to true, I cant seem to find a good example for this in the lit documentation.

So basically:

&lt;my-element foo=&quot;false&quot; /&gt;
...
  @property({type: Boolean})
  foo: boolean;

What I tried allready is try to pass: &quot;${false}&quot;

I created a lit playground link with an example here

答案1

得分: 1

在HTML中,布尔属性由它们是否存在来决定,而不是由字符串值决定。

您应该简单地省略该属性:

<my-element></my-element>

并将属性的默认值设置为false:

class MyElement extends LitElement {
  @property({type: Boolean})
  foo: boolean = false;
}

如果您在lit-html模板中编写标记,您可以使用布尔属性表达式:

let foo = false;
html`<my-element ?foo=${foo}></my-element>`;
英文:

In HTML, boolean attributes are dictated by whether they are present or not, not by the string value.

You should simply omit the attribute:

&lt;my-element&gt;&lt;/my-element&gt;

And default the property to false:

class MyElement extends LitElement {
  @property({type: Boolean})
  foo: boolean = false;
}

If you're writing markup within lit-html templates, you can use the boolean attribute expression.

let foo = false;
html`&lt;my-element ?foo=${foo}&gt;&lt;/my-element&gt;`;

huangapple
  • 本文由 发表于 2023年7月4日 20:33:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76612686.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定