gpt4 book ai didi

Dart Web UI : How do I get a reference to an item within in a web component?

转载 作者:行者123 更新时间:2023-12-03 03:29:29 24 4
gpt4 key购买 nike

如果我在我的应用程序中添加一些 Web 组件,如下面的 myapp.html 所示:

<head>
<link rel="components" href="package:xclickcounter/xclickcounter.html">
</head>
<body>
<div id="container1"><x-click-counter></x-click-counter></div>
<div id="container2"><x-click-counter></x-click-counter></div>
<div id="container3"><x-click-counter></x-click-counter></div>
<div id="container4"><x-click-counter></x-click-counter></div>
...
</body>

我的 Web 组件中有许多元素,如下面的 xclick-counter.html 所示:

<html><body>
<element name="x-click-counter" constructor="CounterComponent" extends="div">
<template>
<button id="button1" on-click="increment()">\\\Increment me</button>
<button id="button2" on-click="decrement()">Decrement me</button>
<span>(click count: {{count}})</span>
</template>
</element>
<!-- more below... -->
</body></html>

如何从 myApp.dart 的#container3 中的 Web 组件中获取对 #button2 的引用?

我希望我可以获得如下引用,但我的引用结果为空:

var reference=document.query('#container1').query('#button2');

最佳答案

通常,您不应尝试这样做。 :) Shadow DOM 是一个封装边界,自定义元素的模板内容应作为实现细节隐藏。将自定义元素想象成一​​个类。你不想进入一个类并看到私有(private)字段,就像你不想进入一个自定义元素并看到 Shadow DOM 中的节点一样。

说了这么多,我想提个建议:

Web UI 当前不保持 ID(来自自定义元素内部)在页面上的唯一性。对于 x-click-counter 的每个实例,页面将具有重复的 button1 和 button2 元素。

我打开了https://github.com/dart-lang/web-ui/issues/492跟踪问题。

解决方法是使用类而不是 ID。然后,您可以为宿主元素指定一个 ID,就像您在代码中所做的那样。尝试更改为:

  <element name="x-click-counter" constructor="CounterComponent" extends="div">
<template>
<button class="button1" on-click="increment()">\\\Increment me</button>
<button class="button2" on-click="decrement()">Decrement me</button>
<span>(click count: {{count}})</span>
</template>
</element>

关于Dart Web UI : How do I get a reference to an item within in a web component?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16345234/

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