【问题标题】:How to extract information from a message of an imported module?如何从导入模块的消息中提取信息?
【发布时间】:2017-05-05 14:53:42
【问题描述】:

我正在尝试以“按钮”示例 (http://elm-lang.org/examples/buttons) 为例,并将其从另一个模块中导入,该模块将在同一页面上显示其中的几个。

恐怕我脑子里还在想组件,但我还是想分享一下。

我创建了 Main.elm,它加载了稍微修改过的按钮示例 (Buttons.elm)。

在 Main.elm 中,我有一个 Buttons.Model 列表,用于生成按钮列表。

我现在卡住了,因为我不知道如何从 Main.elm 中的 Buttons.Msg 获取必要的信息

查看代码:

$ git clone https://github.com/lucamug/elm-multiple-buttons.git
$ cd elm-multiple-buttons/
$ elm-package install
$ elm-reactor

打开

-- 解决方案

正如 Chad Gilber 在接受的答案中指出的那样,问题出在这一行:

(List.indexedMap (\position buttons -> Html.map Tag (Buttons.view position buttons)) model.buttonsList)

这是正确的版本

(List.indexedMap (\position buttons -> Html.map (Tag position) (Buttons.view buttons)) model.buttonsList)

如果您对此实现感兴趣,可以在这篇文章https://medium.com/@l.mugnaini/recycling-elm-code-transforming-it-in-a-module-4946d5ccd3cd中找到更多详细信息

【问题讨论】:

  • 请在问题中粘贴需要考虑的关键代码

标签: functional-programming elm


【解决方案1】:

您需要更新 Tag 构造函数以包含数组索引。

对代码的相关改动是:

view model =
    div []
        (List.indexedMap (\position buttons -> Html.map (Tag position) (Buttons.view position buttons)) model.buttonsList)

type Msg
    = Tag Int Buttons.Msg

update msg model =
    case msg of
        Tag position button_Msg ->

并且您需要在您的 update 函数中删除硬编码的 position = 1

This Pull Request 概述了必要的更改。

【讨论】:

    猜你喜欢
    • 2020-10-17
    • 2021-11-07
    • 2019-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-25
    • 2023-03-28
    相关资源
    最近更新 更多