gpt4 book ai didi

dart - Dart Web 组件如何获取对其子组件的引用?

转载 作者:行者123 更新时间:2023-12-04 23:24:18 25 4
gpt4 key购买 nike

出于说明原因,我创建了一个继承自 WebComponent 的类,名为 FancyOption,该类在单击另一个子元素时更改为由一个子元素中的文本指定的背景颜色。

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>

最佳答案

只需使用 getShadowRoot()并对其进行查询:

import 'package:web_ui/web_ui.dart';
import 'dart:html';

class FancyOptionComponent extends WebComponent {
ButtonElement _button;
TextInputElement _textInput;

inserted() {
// obtain references
_button = getShadowRoot('x-fancy-option').query('.fancy-option-button');
_textInput = getShadowRoot('x-fancy-option').query('.fancy-option-text');

// make the background color of this web component the specified color
final changeColorFunc = (e) => this.style.backgroundColor = _textInput.value;
_button.onClick.listen(changeColorFunc);
}
}

哪里 x-fancy-option字符串是元素的名称。

注意:我将您的构造函数更改为 inserted()方法, which is a life cycle method .

关于dart - Dart Web 组件如何获取对其子组件的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15857141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com