[英]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
装饰器将组件的根元素绑定到此属性。 重要的是要注意这种方法的一些属性:
componentDidLoad
( componentDidLoad
) 后可用。.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>
);
}
}
如果您需要直接引用元素,就像您通常使用 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.