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

Rob*_*een 9 functional-programming frp elm

我想创建一个按钮,当按下该按钮时,会向表单添加一个新输入(或textarea).

sep*_*p2k 10

如果希望每次单击按钮时都添加文本字段,则表示您希望显示的文本字段数等于单击按钮的次数.我们可以创建一个信号,告诉我们使用countIf id按钮clicked信号¹ 点击按钮的频率.

如果我们有一个输入列表,我们可以使用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 []
Run Code Online (Sandbox Code Playgroud)

¹只需使用count就可以计算信号变化的频率.由于每次单击都会使信号的值更改为true,然后再返回到false,这将计算每次点击2次更改.通过使用countIf id我们只计算信号为真的次数,从而计算点击次数.

  • 请注意,Elm不支持信号信号.如果要存储文本字段的输入信号,可以使用Automaton库:http://elm-lang.org/docs/Automaton.elm (4认同)