Web components: How to work with children?

后端 未结 2 1537
慢半拍i
慢半拍i 2021-02-13 17:35

I\'m currently experimenting with StencilJS to create some web components.

Now I know that there is and named slots and all that stuff. Comin

2条回答
  •  面向向阳花
    2021-02-13 18:09

    Using slots you don't need to put a condition in your render function. You can put the no children element (in your example the span) inside the slot element and if no children are provided to the slot it will fall back to it. For example:

    render() {
        return (
            
    no elements
    ); }

    Answering the comment you wrote - you can do such a thing but with some coding and not out of the box. Every slot element has an assignedNodes function. Using that knowledge and the understanding of Stencil component life cycle you can do something such as:

    import {Component, Element, State} from '@stencil/core';
    
    @Component({
        tag: 'slotted-element',
        styleUrl: 'slotted-element.css',
        shadow: true
    })
    export class SlottedElement {
        @Element() host: HTMLDivElement;
        @State() children: Array = [];
    
        componentWillLoad() {
            let slotted = this.host.shadowRoot.querySelector('slot') as HTMLSlotElement;
            this.children = slotted.assignedNodes().filter((node) => { return node.nodeName !== '#text'; });
        }
    
        render() {
            return (
                
      {this.children.map(child => { return
    • ; })}
    ); } }

    This is not an optimal solution and it will require that the style of the slot should have display set to none (cause you don't want to show it). Also, it will only work with simple elements that only need rendering and not requiring events or anything else (cause it only uses them as html string and not as objects).

提交回复
热议问题