【发布时间】:2020-12-13 07:27:45
【问题描述】:
我正在尝试查看自定义元素以及它们是如何工作的,虽然 MDN 上的示例运行良好,但我似乎无法自己复制它们。
MDN 文章是here。
This 是来自 MDN 的一个工作示例。
我的问题是我似乎永远无法将属性传递给我的组件,它们总是以 null 的形式出现,而不是传递参数的值。
我的 JS 是 (test.js)
class PopUpInfo extends HTMLElement {
constructor() {
// Always call super first in constructor
super();
// Create a shadow root
const shadow = this.attachShadow({mode: 'open'});
// Create spans
const wrapper = document.createElement('span');
const info = document.createElement('span');
// Take attribute content and put it inside the info span
const text = this.getAttribute('foo'); // <-- this always returns null
info.textContent = `(${text})`;
shadow.appendChild(wrapper);
wrapper.appendChild(info);
}
}
// Define the new element
customElements.define('popup-info', PopUpInfo);
还有我的 HTML:
<html>
<head>
<script src="test.js"></script>
</head>
<body>
<hr>
<popup-info foo="Hello World"></popup-info>
<hr>
</body>
</html>
我希望在屏幕上看到的是文字
(你好世界)
但我所看到的只是
(空)
当我调试时,我可以看到 this.attributes 的长度为 0,因此它没有被传入。
有没有人在创建自定义元素时见过这种情况?
【问题讨论】:
-
您无法访问
constructor中的DOM 数据,只能在connectedCallback中(或之后)查看:andyogo.github.io/custom-element-reactions-diagram -
啊...这是有道理的。非常感谢链接
标签: javascript html shadow-dom custom-element