出於演示的原因,我創建了一個繼承自WebComponent的類FancyOption,該類更改爲單擊另一個子元素時由一個子元素中的文本指定的背景色。Dart Web組件如何獲取對其子項的引用?
import 'package:web_ui/web_ui.dart';
import 'dart:html';
class FancyOptionComponent extends WebComponent {
ButtonElement _button;
TextInputElement _textInput;
FancyOptionComponent() {
// obtain reference to button element
// obtain reference to text element
// failed attempt
//_button = this.query('.fancy-option-button');
// error: Bad state: host element has not been set. (no idea)
// make the background color of this web component the specified color
final changeColorFunc = (e) => this.style.backgroundColor = _textInput.value;
_button.onClick.listen(changeColorFunc);
}
}
FancyOption HTML:
<!DOCTYPE html>
<html>
<body>
<element name="x-fancy-option" constructor="FancyOptionComponent" extends="div">
<template>
<div>
<button class='fancy-option-button'>Click me!</button>
<input class='fancy-option-text' type='text'>
</div>
</template>
<script type="application/dart" src="fancyoption.dart"></script>
</element>
</body>
</html>
我有他們三個這樣的頁面上。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sample app</title>
<link rel="stylesheet" href="myapp.css">
<link rel="components" href="fancyoption.html">
</head>
<body>
<h3>Type a color name into a fancy option textbox, push the button and
see what happens!</h3>
<div is="x-fancy-option" id="fancy-option1"></div>
<div is="x-fancy-option" id="fancy-option2"></div>
<div is="x-fancy-option" id="fancy-option3"></div>
<script type="application/dart" src="myapp.dart"></script>
<script src="packages/browser/dart.js"></script>
</body>
</html>
我試過了。它不會崩潰,但它現在不渲染組件。它給出了警告: 「_root」不是FancyOptionComponent的成員。 sdk版本0.4.4.4_r20810 – 2013-04-07 20:23:48
哦,現在我知道爲什麼。你應該在'inserted()'中做你的邏輯,而不是在構造函數中。我會更新我的答案。 – 2013-04-07 22:07:20
輝煌。這工作。有趣的是,_root仍然會產生該警告,但程序行爲是我想要的,所以我非常滿意。謝謝,凱。 – 2013-04-07 22:19:37