根据 shadowroot 中元素的 ID 获取标签
Getting tag based on ID of element inside shadowroot
我在发光组件中呈现以下 html:
render() {
return html`
<div class="table">
<div id="col">
<p>testing this component</p>
</div>
</div>`
通过下面的构造函数我正在调用调整大小处理程序:
constructor() {
super();
window.addEventListener('resize', this._handleResize);
}
handleresize方法如下:
private _handleResize = () =>{
var some_id = document.getElementById('col');
var tag = some_id.tagName; ///some_id is coming out as null
}
我正在尝试获取 'col' ID 的标签,但结果为空。有人能告诉我这里有什么错误吗?
您应该使用引用而不是查询元素:
import {ref} from 'lit/directives/ref.js';
[...]
colRef = createRef();
[...]
render() {
return html`
<div class="table">
<div id="col" ${ref(this.colRef)}>
<p>testing this component</p>
</div>
</div>`
}
private _handleResize = () =>{
const col = this.colRef.value!;
const tag = col.tagName;
}
我还建议使用 const
和 let
而不是 var。
此外,您可能应该使用 ResizeObserver
而不是 window
上的事件监听器。
也不要忘记注销您的事件监听器。
我在发光组件中呈现以下 html:
render() {
return html`
<div class="table">
<div id="col">
<p>testing this component</p>
</div>
</div>`
通过下面的构造函数我正在调用调整大小处理程序:
constructor() {
super();
window.addEventListener('resize', this._handleResize);
}
handleresize方法如下:
private _handleResize = () =>{
var some_id = document.getElementById('col');
var tag = some_id.tagName; ///some_id is coming out as null
}
我正在尝试获取 'col' ID 的标签,但结果为空。有人能告诉我这里有什么错误吗?
您应该使用引用而不是查询元素:
import {ref} from 'lit/directives/ref.js';
[...]
colRef = createRef();
[...]
render() {
return html`
<div class="table">
<div id="col" ${ref(this.colRef)}>
<p>testing this component</p>
</div>
</div>`
}
private _handleResize = () =>{
const col = this.colRef.value!;
const tag = col.tagName;
}
我还建议使用 const
和 let
而不是 var。
此外,您可能应该使用 ResizeObserver
而不是 window
上的事件监听器。
也不要忘记注销您的事件监听器。