我是Dart的新手,我想知道我是否可以扩展DivElement类以在一行代码中创建自定义元素 . 我正在寻找这样的东西;
class RedBox extends DivElement {
RedBox(text) {
this.text = text;
this.style.background = "red";
}
}
RedBox myBox = new RedBox("Hello World");
document.body.append(myBox);
当然,我将拥有更复杂的元素和自定义函数 . 但总的来说,这可能吗?
当我尝试运行时,我得到:
implicit call to super constructor 'DivElement()'
2 回答
您可以扩展HTML元素,但有一些要求 . 你现在遇到的是你需要一个
RedBox.created
构造函数,它只能重定向到它的超类 .created
必须是唯一的生成构造函数,但您可以添加工厂构造函数 .另一个要求是该元素已注册document.registerElement .
尝试添加此:
关于扩展HtmlElement的一些注意事项 .
示例:https://api.dartlang.org/1.14.1/dart-html/HtmlDocument/registerElement.html
陷阱:
解决方案(假设扩展PreElement):
使用'document.registerElement(' xxx ', XXX, extendsTag:' pre ');'和'new Element.tag(' pre ',' xxx ');'
Dart目前不支持库初始化 . 您必须在main中调用document.registerElement .
测试1.14.0