[英]Cannot get web component to work in codesandbox.io
I'm trying to get a customized built-in web component to work in codesandbox.io. 我正在尝试获得一个自定义的内置Web组件,以在codeandbox.io中工作。 This is the code:
这是代码:
class MyDiv extends HTMLDivElement { constructor() { super(); } connectedCallback() { this.innerHTML = "works!"; } } customElements.define("my-div", MyDiv, {extends: 'div'});
<div is="my-div"></div>
The error I'm getting: 我得到的错误:
Failed to construct 'HTMLDivElement': Please use the 'new' operator, this DOM object constructor cannot be called as a function.
Tested in Chrome 67, Arch Linux. 已在Arch Linux的Chrome 67中进行了测试。 Here's the link: https://codesandbox.io/s/yqln560jzj
这是链接: https : //codesandbox.io/s/yqln560jzj
It does work here in a snippet, and it also works on codepen: https://codepen.io/connexo/pen/ZjEbqo 它确实可以在代码段中运行,也可以在Codepen上运行: https ://codepen.io/connexo/pen/ZjEbqo
What am I missing here? 我在这里想念什么?
If it doesn't works it's because Codesandbox is using a kind a Javascript preprocessor (Typescript?) on external JS files, that will execute the code before (to detect syntaxt errors or so on). 如果它不起作用,是因为Codesandbox在外部JS文件上使用了一种Javascript预处理程序(Typescript?),它将在执行该代码之前(以检测语法错误等)。
The customElements.define()
method is called twice, and fails the second time it is called because you can define a custom element only one time. customElements.define()
方法被调用两次,第二次调用失败,因为您只能定义一个自定义元素。
You can see it by calling customElements.get()
inside your script, and see it's already defined. 您可以通过在脚本内调用
customElements.get()
来查看它,并查看它是否已定义。
console.log( customElements.get( 'my-div' ) )
If you put the Javascript inline (in the HTML file index.html ) in a element it will work fine. 如果将Javascript内联(在HTML文件index.html中 )放在一个元素中,它将正常工作。
Note that the second error you get it's because you are using the Babel preprocessor in the Codeopen snippet. 请注意,您得到的第二个错误是因为您在Codeopen代码段中使用了Babel预处理程序。 You must disable Babel and it will work.
您必须禁用Babel才能使用。
What am I missing here?
我在这里想念什么?
Nothing. 没有。 It's codesandbox.io that is missing Custom Elements support.
缺少自定义元素支持的是codesandbox.io。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.