有一种方法可以让NodeList标记在Mithril中吗?我要知道街区的宽度。就像香草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';发布于 2022-05-14 15:21:34
对于典型的DOM脚本,DOM元素是预先存在的,您需要确保它们有可识别的选择器(在本例中是blocks类),然后在其他地方使用该选择器获得document.querySelectorAll对它们的Javascript引用。
但是对于Mithril,您在相同的位置声明和引用DOM元素,因此您不需要这些方法中的任何一个:而是在适当的节点上附加一个生命周期法并保存对局部变量的引用。
生命周期方法公开一个表示虚拟DOM实体的vnode参数:它包含一个dom属性,该属性公开呈现的DOM元素。
在组件中保存引用的基本机制如下:
function MyComponent(){ // The component to contain the logic
let dom // The variable to store our DOM reference
return {
view : () =>
m('.MyElement', { // The virtual DOM element
oncreate(vnode){ // The `oncreate` lifecycle method to access the `vnode`
dom = vnode.dom // Save the dom reference to our variable
}
})
}
}下面,我编写了一个小沙箱演示程序,它在一个稍微复杂的场景中使用您的宽度计算脚本:这里有一个可变数量的块,随着时间的推移被添加和删除;我们声明一个Set来存储它们,对于每一个条目,我们声明一个oncreate方法来将它放到集合中,一个onremove来存储它。我使用毁伤直接从方法中提取dom引用;稍后,我们使用稍微修改过的宽度积累代码版本,使用Array.from的第二个参数提取width。
function Blocks(){
const blocks = new Set
return {
view: ({attrs: {count}}) => [
m('.container',
Array.from({length: count}, (_, index) =>
m('.block', {
oncreate({dom}){
blocks.add(dom)
},
onremove({dom}){
blocks.delete(dom)
},
}, index + 1)
),
),
m('button', {
onclick(){
const styles = Array.from(
blocks,
(item) => item.getBoundingClientRect().width
)
const widthOfTheBlocks = styles.reduce((acc, curr) => acc + curr, 0) + 'px';
alert(widthOfTheBlocks)
}
}, 'Alert width'),
]
}
}
m.mount(document.body, function App(){
let count = 1
return {
view: () => [
m('h1', 'Width reader'),
m('label',
'Number of blocks: ',
m('input[type=number][min=0][max=9][size=4]', {
value: count,
oninput(e){
count = e.target.value
},
}),
),
m(Blocks, {count}),
]
}
}).container {
display: flex;
margin: 1em 0;
}
.block {
flex: 0 0 25%;
padding: 1em;
border: 1px solid;
}<script src="https://unpkg.com/mithril/mithril.js"></script>
https://stackoverflow.com/questions/72234710
复制相似问题