我有以下网络组件:
我最初在本地测试了这个(在 create-react-app 中)没有工作。然后我将它放入codesandbox(反应模板)中,它也不起作用。
class CounterWebComponent extends HTMLElement {
constructor() {
console.log("ctor");
super();
}
_count: number = 0;
set count(value: number) {
console.log("CounterWebComponent set", value);
this._count = value;
}
get count() {
console.log("CounterWebComponent get", this._count);
return this._count;
}
connectedCallback() {
console.log("CounterWebComponent connected");
this.innerHTML = "<h1>fff</h1>";
}
disconnectedCallback() {
console.log("CounterWebComponent disconnected");
}
}
if (!customElements.get("counter-wc-custom"))
customElements.define("counter-wc-custom", CounterWebComponent);
在index.html中我试图设置计数:
<counter-wc-custom id="counter1"></counter-wc-custom>
<script>
const counter2 = document.getElementById("counter1");
counter2.count = 23;
alert(counter2.count);
alert(counter2._count); //using alert because console.log inside index.html is not working for some reason in codesandbox
console.log("count", counter2.count);
console.log("_count", counter2._count);
counter2.addEventListener("count", (e) => console.log(e));
</script>
如果我像这样使用它,它会起作用:
const a = document.createElement("counter-wc-custom");
a.count = 2;
console.log("count", a.count);
console.log("_count", a._count);
编辑:https://codesandbox.io/s/react-web-component-custom-wrapper-xh2n9s(我像个白痴一样忘记了链接)
我假设我在某个地方错误地配置了某些东西,但我不知道是什么。如有任何帮助,我们将不胜感激。
Codesandbox 对于显示大多数日志来说并不可靠(不知道为什么), 我删除了一些样板文件(反应部分)并在SO中创建了一个
snippet
,你可以看到你的代码有效 - 我删除了_count
,因为它不需要(如果你不关心变量的隐私)
但是您可以检查您的方法是否有效(
set
和get
日志都在那里):
class CounterWebComponent extends HTMLElement {
static get observedAttributes() {
return ["count"];
}
constructor() {
console.log("CounterWebComponent");
super();
}
set count(value) {
console.log("CounterWebComponent set", value);
}
get count() {
console.log("CounterWebComponent get");
return this.getAttribute("count");
}
connectedCallback() {
console.log("CounterWebComponent connected");
this.innerHTML = `<h1>fff: ${this.count}</h1>`;
}
disconnectedCallback() {
console.log("CounterWebComponent disconnected");
}
}
if (!customElements.get("counter-wc-custom"))
customElements.define("counter-wc-custom", CounterWebComponent);
const counter = document.getElementById("counter1");
console.log(counter.count);
counter.count = 35;
<div id="app"></div>
<counter-wc-custom id="counter1" count="50"></counter-wc-custom>
我认为你应该像这样更新index.html。
document.addEventListener("DOMContentLoaded", function() {
const counter2 = document.getElementById("counter1");
counter2.count = 23;
console.log("count", counter2.count);
console.log("_count", counter2._count);
counter2.addEventListener("count", (e) => console.log(e));
});
<counter-wc-custom id="counter1"></counter-wc-custom>