我意识到我一定在某个地方遗漏了一个论点,或者我的一个论点是不正确的,但是在尝试了我能想到的一切之后,我不知道该怎么做。
handleKeyDown : msg -> Attribute (Int -> Msg)
handleKeyDown message =
custom "keydown" (Json.succeed { message = KeyPressed, stopPropagation = True, preventDefault = True })
view : Model -> Html Msg
view model =
div []
[ input
[ handleKeyDown ]
[ text "" ]
]
错误
The 1st argument to `input` is not what I expect:
104| [ input
105|> [ handleKeyDown ]
106| [ text "" ]
This argument is a list of type:
List #(msg -> Attribute (Int -> Msg))#
But `input` needs the 1st argument to be:
List #(Attribute msg)#
最佳答案
这里有几个问题:
handleKeyDown
需要一个您不使用且不传递的message
参数。因此,类型是msg -> Attribute ...
而不是预期的Attribute ...
。KeyPressed
似乎具有Int
类型的有效负载。因此返回值是Attribute (Int -> Msg)
而不是Attribute Msg
。
假设您想使用 message
参数并从事件中获取 keyCode
,这应该可行:
handleKeyDown : (Int -> Msg) -> Html.Attribute Msg
handleKeyDown tag =
let
options message =
{ message = message
, stopPropagation = True
, preventDefault = True
}
decoder =
Json.field "keyCode" Json.int
|> Json.map tag
|> Json.map options
in
Html.Events.custom "keydown" decoder
view : Model -> Html Msg
view model =
div []
[ input
[ handleKeyDown KeyPressed ]
[ text "" ]
]
这里,handleKeyDown
需要一个带有 Int
负载的标签/消息。内部事件解码器检索 keyCode
,将其包装在您传入的标记中,然后使用 preventDefault = True
将其包装在选项对象中。
但请注意 keyCode
已被弃用,您可能想使用 code
或 key
来代替,它们都是字符串。
关于events - 尝试阻止默认时自定义 keydown 事件的类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55992579/