gpt4 book ai didi

javascript - Mithril 组件组合中单独单击增量按钮

转载 作者:行者123 更新时间:2023-12-01 02:43:19 24 4
gpt4 key购买 nike

我对 Mithril.js 中组件的组成方式感到困惑。在下面的示例中,我创建了一个按钮组件,用于保存按钮点击次数的私有(private)计数。如果我将两个这样的组件(下面的按钮 1 和 2)分别安装到两个安装点(下面的“m1”和“m2”),我可以分别正确地初始化和增加按钮点击次数。

但是,如果我将两个按钮组件(下面的按钮 3 和 4)包装在一个较大的组件内,并将该包装组件安装到安装点(“m3”),则按钮点击次数根本不会增加。这里出了什么问题以及如何修复它?

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://unpkg.com/mithril/mithril.js"></script>
</head>

<body>
<h1>This works:</h1>
<div id="m1"></div>
<div id="m2"></div>
<h1>This doesn't work:</h1>
<div id="m3"></div>

<script>
// The factory method to generate a button component
function createButton(options) {
let {title, count} = options;
return {view: () => [
m("span", title),
m("button", {onclick: function() {count++}}, count + " clicks"),
]};
};

(function() {
// this works
m.mount(document.getElementById("m1"), createButton({title: "button 1 ", count: 0}));
m.mount(document.getElementById("m2"), createButton({title: "button 2 ", count: 10}));

// this doesn't work
m.mount(document.getElementById("m3"), {view: () => [
m("div", [m(createButton({title: "button 3 ", count: 0}))]),
m("div", [m(createButton({title: "button 4 ", count: 10}))]),
]});
})();
</script>
</body>
</html>

最佳答案

第二个版本是在每次重绘时创建一个具有全新参数的全新组件,因此每次事件时都会删除 count 值。

如果你改用 Mithril 的closure components它会满足您的需求。

// Button closure component
function createButton(vnode) {
let {title, count} = vnode.attrs;

return {
view: () => [
m("span", title),
m("button", {onclick: function() {count++}}, count + " clicks"),
]
};
};

(function() {
m.mount(document.getElementById("m3"), {view: () => [
m("div", [m(createButton, {title: "button 3 ", count: 0})]),
m("div", [m(createButton, {title: "button 4 ", count: 10})]),
]});
})();

https://jsbin.com/mazujij/2/edit?js,output

关于javascript - Mithril 组件组合中单独单击增量按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47406721/

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