繁体   English   中英

如何在 Stenciljs 中获取 DOM 元素?

[英]How to get a DOM element in Stenciljs?

import { Component, Prop } from '@stencil/core';
@Component({
    tag: 'my-component',
    styleUrl: 'my-component.css',
    shadow: true
})
export class MyComponent {

  @Prop() first: string;
  @Prop() last: string;
  getElementHere() {
     // how can I get the div here?
  }
  render() {
    return (
      <div>
        Hello, World! I'm {this.first} {this.last}
      </div>
    );
  }
}

我想像在原生 JS 中一样获取 DOM 元素。 你如何在 Stencil 中做到这一点? getElementById不起作用。

为了扩展 Fernando 的答案,@ @Element装饰器将组件的根元素绑定到此属性。 重要的是要注意这种方法的一些属性:

  1. @Element 绑定属性仅在加载componentDidLoad ( componentDidLoad ) 后可用。
  2. 由于该元素是标准 HTMLElement,您可以使用标准.querySelector(...).querySelectorAll(...)方法访问当前组件中的元素以检索和操作它们。

这是一个示例,显示元素何时可访问,以及如何操作此元素内的节点(从模板 0.7.24 开始更正):

import { Component, Element } from '@stencil/core';

@Component({
    tag: 'my-component'
})
export class MyComponent {

    @Element() private element: HTMLElement;
    private data: string[];

    constructor() {
        this.data = ['one', 'two', 'three', 'four'];
        console.log(this.element); // outputs undefined
    }

    // child elements will only exist once the component has finished loading
    componentDidLoad() {
        console.log(this.element); // outputs HTMLElement <my-component ...

        // loop over NodeList as per https://css-tricks.com/snippets/javascript/loop-queryselectorall-matches/
        const list = this.element.querySelectorAll('li.my-list');
        [].forEach.call(list, li => li.style.color = 'red');
    }

    render() {
        return (
            <div class="my-component">
                <ul class="my-list">
                    { this.data.map(count => <li>{count}</li>)}
                </ul>
            </div>
        );
    }
}

您可以获取当前的 HTML 元素,将其作为属性添加到您的组件中:

@Element() myElement: HTMLElement;

您可以在此处阅读有关此内容的更多信息

希望这对你有帮助:)

来自官方文档

如果您需要直接引用元素,就像您通常使用 document.querySelector 所做的那样,您可能希望在 JSX 中使用 ref。

所以在你的情况下:

import { Component, Prop } from '@stencil/core';
@Component({
    tag: 'my-component',
    styleUrl: 'my-component.css',
    shadow: true
})
export class MyComponent {

  @Prop() first: string;
  @Prop() last: string;

  divElement!: HTMLElement; // define a variable for html element

  getElementHere() {
    this.divElement  // this will refer to your <div> element
  }

  render() {
    return (
      <div ref={(el) => this.divElement= el as HTMLElement}> // add a ref here
        Hello, World! I'm {this.first} {this.last}
      </div>
    );
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM