我创建了一个非常基本的自定义元素,可以根据提供的属性person
更改其值。但是,每当我加载自定义元素时,都会出现此错误:Cannot set property 'innerHTML' of null
。当我向attributeChangedCallback函数添加断点时,确实可以看到加载时该元素不存在。当我继续加载时,尽管元素加载完美。
我可以想象,因为我正在使用webpack捆绑我的所有文件,所以问题出在将元素加载到主体的末端而不是将元素加载到我的头上。
my-element.js:
class MyElement extends HTMLElement {
constructor() {
super();
this.shadow = this.attachShadow({mode: 'open'});
this._person = '';
}
get person() {
return this._name;
}
set person(val) {
this.setAttribute('person', val);
}
static get observedAttributes() {
return ['person'];
}
attributeChangedCallback(attrName, oldVal, newVal) {
let myElementInner = this.shadow.querySelector('.my-element-inner');
switch (attrName) {
case 'person':
this._person = newVal;
// ======================
// The error occures here
// ======================
myElementInner.innerHTML = `My name is ${this._person}`;
}
}
connectedCallback() {
var template =
`
<style>
.my-element-inner {
outline: blue dashed 1px;
background-color: rgba(0,0,255,.1);
}
</style>
<span class="my-element-inner">My name is ${this._person}</span>
`
this.shadow.innerHTML = template;
}
}
customElements.define('my-element', MyElement);
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>WebPack Test Page</title>
</head>
<body>
<my-element person="André"></my-element>
<!-- Here goes the bundle.js -->
</body>
</html>
答案 0 :(得分:2)
可以根据自定义元素的使用方式在attributeChangedCallback()
之前或之后调用connectedCallback
。
如果将connectedCallback
逻辑移到构造函数中,一切都会好起来
另一种选择是检查myElementInner
是否为null
并将您的代码保存在connectedCallback
class MyElement extends HTMLElement {
constructor() {
super();
this.shadow = this.attachShadow({mode: 'open'});
this._person = '';
var template =
`
<style>
.my-element-inner {
outline: blue dashed 1px;
background-color: rgba(0,0,255,.1);
}
</style>
<span class="my-element-inner">My name is ${this._person}</span>
`
this.shadow.innerHTML = template;
}
get person() {
return this._person;
}
set person(val) {
this.setAttribute('person', val);
}
static get observedAttributes() {
return ['person'];
}
attributeChangedCallback(attrName, oldVal, newVal) {
let myElementInner = this.shadow.querySelector('.my-element-inner');
switch (attrName) {
case 'person':
this._person = newVal;
if (myElementInner) {
myElementInner.innerHTML = `My name is ${this._person}`;
}
}
}
}
customElements.define('my-element', MyElement);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>WebPack Test Page</title>
</head>
<body>
<my-element person="André"></my-element>
<!-- Here goes the bundle.js -->
</body>
</html>