我正在开发我的第一个 Dart 应用程序,已经完成了 Dart 游戏教程。我正在尝试创建一个语义命名的顶级菜单元素,该元素最终将在我的页面顶部显示导航菜单选项卡列表。我的 Dart 应用程序能够识别我的自定义元素并调用关联的构造函数。
但是,当我尝试在我的自定义元素中查询 UL 元素时,我得到了一个空引用。我需要 UL 引用才能将我的 LI 元素动态加载到菜单中。
问题一: 元素是否应该在构造函数运行时在 DOM 中可见?
问题二: 如果它还不可见,在自定义元素完全加载到 DOM 中后,是否可以使用 Dart 事件来触发加载 LI 元素?
提前致谢!作为引用,这里是我的自定义元素的来源:
topmenu-element.html
<!DOCTYPE html>
<html>
<body>
<element name="top-menu" constructor="TopMenu" extends="div">
<template>
<div>
Top Menu
<ul id="top-menu-list"></ul>
</div>
</template>
<script type="application/dart" src="topmenu-element.dart"></script>
</element>
</body>
</html>
topmenu-element.dart
import 'package:web_ui/web_ui.dart';
import 'dart:html';
class TopMenu extends WebComponent {
List menuItems = ['Session', 'Authentication Services', 'Vehicle Services', 'Subscriber Services', 'Data Services'];
void populateMenu() {
UListElement menuList = query('#top-menu-list');
LIElement newMenuItem = new LIElement();
newMenuItem.text = menuItems[0];
menuList.children.add(newMenuItem);
}
TopMenu() {
// populateMenu();
}
}
最佳答案
我不能具体谈论带有查询方法的构造函数中的 DOM 可见性,因为我确实不确定。然而,也许有更好的方法可以使用,这些方法在 elements lifecycle 的不同阶段被调用。 .
也就是说,我能问一下为什么你需要使用这种特殊的方法来添加 child 吗?使用 template repeat 可能更容易做到这一点像这样:
<!DOCTYPE html>
<html>
<body>
<element name="top-menu" constructor="TopMenu" extends="div">
<template>
<div>
Top Menu
<ul id="top-menu-list">
<li template repeat="item in menuItems">{{item}}</li>
</ul>
</div>
</template>
<script type="application/dart" src="topmenu-element.dart"></script>
</element>
</body>
</html>
那么就不需要将任何菜单显示代码放在构造函数中。
关于dart - 自定义元素 - 来自构造函数中 query() 的空引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15975325/