如何从 Elm 中的组件调用 parent 消息?

How to call a parent msg from component in Elm?

我有一个模式 window 可以在其中显示不同的组件。每个组件都有自己的更新程序和消息,但我想在它们之间共享一个关闭按钮。

因此我不能直接从我的 children 呼叫 "CloseModal" — Elm 不允许我呼叫其他人消息。我有哪些选择?


我以为我可以调用 "Modal.Update.update Modal.Messages.CloseModal",但在我的组件内部我只有状态块。所以这不是一个选择。

然后我找到了一种将消息从 parent 传递到 child 的方法,但它无法帮助我以其他方式传递消息。或者给兄弟姐妹。

简而言之,您不能将消息直接从 child 传递给 parent 或兄弟姐妹。

Elm 架构实现 uni-directional 消息传递,换句话说,您的 parent 组件在 child 组件收到消息之前始终知道 child 组件的消息.

我做了一个简单的example of parent-child communication,它太大了,无法将其嵌入到答案中,因此我将在这里只标记要点。

Child

Child 组件定义了一个 set of Messages:

type Msg
    = Update Model
    | Focus
    | Blur

在它的 update 函数中,我们 ignore 消息,用于 parent 组件。

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        Update value ->
            ( value, Cmd.none )

        -- Ignore the rest of the messages.
        _ ->
            ( model, Cmd.none )

Parent

在 parent 的 update 函数中,我们可以模式匹配所需的消息并对它们做出反应。

其余消息将通过 default branch

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        NameMsg childMsg ->
            case childMsg of
                {- We have intercepted a message from child component.
                   This part of the update function might be moved
                   to a separate function for better readability.
                -}
                Input.Focus ->
                    update (HelperMsg Helper.Show) model

                Input.Blur ->
                    update (HelperMsg Helper.Hide) model

                -- The default message passing routine.
                _ ->
                    let
                        ( nameModel, nameCmd ) =
                            Input.update childMsg model.name
                    in
                        ( { model | name = nameModel }
                        , Cmd.map NameMsg nameCmd
                        )

上面的例子结束了child-parent和兄弟姐妹的交流。您可以 运行 更新功能递归地使用任何消息到任何组件。

从 child 的 update 函数发送消息

Cmd.Extra公开了一个发送消息的函数。

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model ->
    (model, message SomeMessage)

PS: 翻译器模式示例在我的 To-do 上,如果您希望我用它更新答案,请发表评论。