【问题标题】:How Do I make an Elm-UI element respond to pressing "Enter"如何使 Elm-UI 元素响应按“Enter”
【发布时间】:2019-08-23 22:37:42
【问题描述】:

我需要让我的应用在按下 Enter 时发送一条消息。我有一个类似的元素:

Input.text [] { onChange = UpdateText, text = model.text, placeholder=Nothing }

按下回车后如何提交?

注意:Q/A 复制自 Elm-Slack 以方便查找。

【问题讨论】:

    标签: elm elm-ui


    【解决方案1】:

    Elm-UI docs 中提到了这一点。

    基本上,您定义一个函数,当按下 Enter 键时发送一个 msg 并将其嵌入到您的 view 函数中:

    onEnter : msg -> Element.Attribute msg
    onEnter msg =
        Element.htmlAttribute
            (Html.Events.on "keyup"
                (Decode.field "key" Decode.string
                    |> Decode.andThen
                        (\key ->
                            if key == "Enter" then
                                Decode.succeed msg
    
                            else
                                Decode.fail "Not the enter key"
                        )
                )
            )
    

    然后将其嵌入到视图中元素的属性中:

    Input.text
        [ onEnter EnterWasPressed ]
        { onChange = UpdateText
        , text = model.text
        , placeholder = Nothing
        }
    

    Ellie Link(来自文档):https://ellie-app.com/5X6jBKtxzdpa1

    【讨论】:

    • 这似乎是一件奇怪的事情。我想知道为什么。
    • 如果我不想触发 onChange 怎么办?由于在 elm-ui 中 onChange 是强制性的,我仍然需要一个在 update 函数中什么都不做的 Message 标签?很奇怪。
    猜你喜欢
    • 2010-09-25
    • 2016-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-02
    • 2019-07-30
    • 2018-08-18
    • 1970-01-01
    相关资源
    最近更新 更多