我们可以使用带有slot的stencilJS元素,如下所示
<my-component>123</my-component>我正在尝试从我的render方法本身获取123的值,想知道这是否可能?
@Component({ tag: 'my-component' })
export class MyComponent {
render() {
return (
<div><slot /></div>
)
}
}我想在123上进行一些字符串格式化,而不是直接呈现slot
发布于 2020-10-14 20:37:53
import { Element } from '@stencil/core';
@Component({ tag: 'my-component' })
export class MyComponent {
/**
* Reference to host element
*/
@Element() host: HTMLElement;
componentWillRender() {
console.log(this.host.innerHTML)
}
render() {
return (
<div><slot /></div>
)
}
}
发布于 2020-12-28 10:19:42
在web组件中,其中的内容也是主DOM的一部分。如果不使用插槽,这个内容就不会显示出来;但是,无论如何,这个内容都会投射到#shadow-root旁边(使用“元素”部分中的chrome developer工具来查看)。

因此,如果不想使用默认插槽显示内容,可以使用属性装饰器@Element()并声明一个HTMLElement类型的属性:
然后,您可以通过innerHTML或innerText访问内容。
最后,您可以格式化内容。检查下面的代码片段:
import { Component, Element, h } from "@stencil/core";
@Component({
tag: 'my-component',
styleUrl: 'my-component.css',
shadow: true
})
export class MyComponent {
@Element() element: HTMLElement;
formatContent(content: any) {
if ( isNaN(content)){
// Your format here
return content;
} else {
return content + '.00';
}
}
render() {
return [
// Commented slot tag
// <slot></slot>,
<div> {this.formatContent(this.element.innerHTML)} </div>
];
}
}使用具有2个字符串和一个数字的三次web组件作为条目数据,结果应该是:
My text
My text 2
123.00https://stackoverflow.com/questions/64311361
复制相似问题