如何在Elm中动态创建输入框?

9
我希望创建一个按钮,按下它后,表单会增加一个新的输入框或文本域。
2个回答

10
如果您希望每次单击按钮时添加一个文本字段,这意味着您希望显示的文本字段数量等于单击按钮的次数。我们可以使用按钮的“clicked”信号¹上的“countIf id”来创建一个告诉我们按钮已被点击多少次的信号。
如果我们有输入列表,我们可以使用“flow”将它们显示在彼此下方(或旁边)。编写一个函数以获取数字“n”,并生成包含一个按钮和“n”个文本字段的列表非常简单。
现在我们只需使用“lift”将该函数连接到计算按钮点击次数的信号上,与“flow”函数相结合,就可以轻松地创建动态创建输入的按钮了。
(btn, clicked) = Input.button "Click me!"

-- Count how often the clicked signal is true
clicks = countIf id clicked

main = lift2 flow (constant down) $ lift nInputs clicks

nInputs n =
  let helper n acc =
    if n<=0 then btn : acc
    else
      -- Input.textField returns a pair containing the field as well as a signal
      -- that you can use to access the field's contents. Since I don't actually
      -- ever do anything with the contents, I just ignore the signal here.
      -- In your real code, you'd probably want to keep the signal around as well.
      let (field, _) = Input.textField $ "input " ++ (show n)
      in helper (n-1) $ field : acc
  in helper n []

仅使用count将计算信号更改的次数。由于每次点击都会导致信号的值从true更改为false,然后再次更改回来,因此每次点击会计算2次更改。通过使用countIf id,我们只计算信号为true的次数,因此计算点击次数。


4
请注意,Elm不支持信号的信号。如果您想存储文本字段的输入信号,可以使用Automaton库:http://elm-lang.org/docs/Automaton.elm - thSoft

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接