Sma*_*Man 6 javascript 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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
我想像在原生 JS 中一样获取 DOM 元素。你如何在 Stencil 中做到这一点?getElementById不起作用。
为了扩展 Fernando 的答案,@Element装饰器将组件的根元素绑定到此属性。重要的是要注意这种方法的一些属性:
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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
如果您需要直接引用某个元素(就像通常使用 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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10359 次 |
| 最近记录: |