我需要渲染不同的html基于布尔变量true或false的值。例如,在react中,我会在render函数的返回值中这样做:
{this.state.booleanValue ? "true" : "false"}根据booleanValue的值,我得到了两种不同的输出。
我在Polymer 3中尝试过,并首先声明了我的bool变量:
static get properties() {
return {
myBoolValue: {
type: Boolean
}
};
}然后,我尝试在我的template/html中使用它作为
${this.myBoolValue ? "" : ""}但是,代码不能识别html模板中的变量"this.myBoolValue“。怎么会这样?我的模板的完整代码:
static get template() {
return html`
<div>
${this.myBoolValue ? "true" : "false"} // error, does not recognize "this.myBoolValue".
</div>
`;发布于 2021-03-11 03:58:37
如果myBoolValue的默认值是false,您可以像这样更改属性和模板(如果您想使用conditional templates,则必须导入@polymer/polymer/lib/elements/dom-if.js)。
static get properties() {
return {
myBoolValue: {
type: Boolean,
value: false
}
};
}
static get template() {
return html`
<p>[[myBoolValue]]</p>
// OR conditional templates:
<template is="dom-if" if="{{myBoolValue}}">
true
</template>
<template is="dom-if" if="{{!myBoolValue}}">
false
</template>
`;
}如果您不能或不想设置默认值,请像这样更改代码并使用computed property
static get properties() {
return {
myBoolValue: {
type: Boolean
},
computedBool: {
type: String,
computed: "_isTrue(myBoolValue)",
value: false
}
};
}
static get template() {
return html`
<p>[[computedBool]]</p>
<template is="dom-if" if="{{computedBool}}">
true
</template>
<template is="dom-if" if="{{!computedBool}}">
false
</template>
`;
}
_isTrue(a) {
return a === true;
}https://stackoverflow.com/questions/66436706
复制相似问题