在Mithril中获取HTML标签的结节性
有没有一种方法可以在Mithril中拥有HTML标签的结节性?我需要获得块的宽度。在香草JS上这样的东西:
const blocks = Array.from(document.querySelectorAll('.blocks'));
const styles = blocks
.map((item) => item.getBoundingClientRect())
.map((item) => item.width);
const widthOfTheBlocks = styles.reduce((acc, curr) => acc + curr, 0) + 'px';
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于典型的DOM脚本,DOM元素是预先存在的,您需要确保它们具有可识别的选择器(在这种情况下为
blocks
类),然后在其他地方使用该选择器获得Javascript用document.queryselectorall
引用它们。但是使用Mithril,您正在声明并引用同一位置的DOM元素,因此您不需要以下任何一种方法:而是附加
生命周期方法公开a
vnode 实体:这包含一个
dom
属性,该属性暴露了渲染的dom元素。在组件中保存参考的基本机制如下:
下面,我写了一个小的沙盒演示,该演示使用您的宽度计算脚本在稍微复杂的情况下:这里有一个可变数量的块,这些块已添加到和随着时间的流逝而删除;我们声明A 要存储它们,对于每个项目,我们将
ongreate
方法添加将其添加到集合中,然后将 onremove 添加到>删除
it。我已经使用 dom 参考;后来,我们使用array.from
提取width
。With typical DOM scripting, the DOM elements are pre-existing, and you would need to make sure they had identifiable selector (in this case the
blocks
class), and then elsewhere use that selector to get a Javascript reference to them, withdocument.querySelectorAll
.But with Mithril, you're declaring and referencing the DOM elements in the same place, so you don't need either of these methods: instead you attach a lifecycle method on the appropriate node and save the reference to a local variable.
The lifecycle methods expose a
vnode
argument representing the virtual DOM entity: this contains adom
property which exposes the rendered DOM element.The essential mechanism to save a reference inside a component is as follows:
Below, I've written a little sandbox demo that uses your width calculation script in a slightly more complex scenario: Here there's a variable number of blocks, which are added to and removed over time; we declare a
Set
to store them, and for each item we declare anoncreate
method toadd
it to the set, and anonremove
todelete
it. I've used destructuring to extract thedom
reference straight from the methods; later, we use a slightly tweaked version of your width accumulation code, using the 2nd argument ofArray.from
to extract thewidth
.