typescript - 在 TypeScript 和 HTML 中定义、导入和使用自定义元素
问题描述
我正在尝试定义一个自定义元素并在 HTML 模板中使用它,但它没有显示,控制台没有记录任何内容。似乎元素没有以这种方式定义。
我究竟做错了什么?我正在使用 webpack 和 TypeScript。
我在 top-bar.ts 中定义了一个扩展 HTML 元素的类
export class TopBar extends HTMLElement {
shadowDOM : ShadowRoot;
constructor() {
super();
console.log('from constructor');
this.shadowDOM = this.attachShadow({mode:"open"});
}
connectedCallback() : void {
this.render();
}
render() : void {
this.innerHTML = `
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<style>
.top-bar {
box-shadow: 0px 2px 10px 6px #ccc;
height: 40px;
}
.top-bar h5 {
margin-bottom: 0;
color: #273C75;
}
.top-bar img {
display: block;
width: 36px;
height: 36px;
margin-right: 0.5rem;
}
</style>
<nav class="top-bar d-flex justify-content-center align-items-center">
<img src="img/Beep-Signal.png" alt="">
<h5>LoRa Dashboard</h5>
</nav>
`
}
}
customElements.define("top-bar", TopBar);
在 index.ts 中,我导入了 TopBar。
import * as TopBar from './components/top-bar'
在 index.html 中,我放置了 top-bar 元素
<!DOCTYPE html>
<html>
<head>
<title>LoRa Dashboard</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
<body>
<script src="bundle.js"></script>
<top-bar></top-bar>
</body>
</html>
解决方案
所以过了一会儿,我终于发现 top-bar.ts 似乎没有包含在包中。
尽管我已在 index.ts 中导入了 top-bar,但似乎没有包含 top-bar,我的怀疑是因为在 index.ts 中的任何地方都没有使用 top-bar.ts 中的任何内容,仅在 HTML 中(测试时)。这就是为什么自定义元素永远不会被定义的原因。
所以我在 top-bar.ts 中添加了一个虚拟函数,并在 index.ts 中调用它只是为了将其包含在内。这目前适用于我的项目,而且我是 TypeScript 和 JavaScript 的新手,但我确信有更好的解决方法,而不是仅仅为了包含它而调用一个虚拟函数。
推荐阅读
- android-studio - 为什么我没有收到错误并且应用程序无法打开
- sql - 将字符串类型的日期和时间连接到一个 TIMESTAMP 列 [Impala]
- variables - 在 TFS 2018 Release Task 之间传递一个变量,然后在门步骤中使用该变量
- node.js - req.body 始终是一个空对象
- python - 一旦在python中打开一个变量分配给一个文件,当重新分配变量时文件会发生什么?
- ios - 无法在 pubspec.yaml 中添加依赖项而不会在 Flutter ios 开发中出错
- node.js - 使用库二进制解析器的节点 js 的二进制文件解析问题
- webrtc - Chrome webrtc-internals 显示 audioLevel 为 0 并且没有音频
- c# - 统一旋转触摸对象
- ruby - gem 在 OSX 10.15 上安装 therubyracer -v 0.12.3