Elm中拆分Msg类型后,如何将Html Msg1转换为Html Msg?
Great question! When splitting your Elm app into modular sub-components with their own Model and Msg types, the perfect tool to bridge the gap between Html Msg1 and Html Msg is the Html.map function—it’s built specifically for this scenario.
How It Works
Html.map takes two things:
- A function that converts your sub-component’s message type (like
Msg1) into the parent message type (likeMsg, via theM1wrapper variant). - The sub-component’s view output (
Html Msg1).
It then transforms every message emitted by the sub-view into a valid parent message, turning Html Msg1 into Html Msg.
Modified Code Example
Here’s how to adjust your existing code to use Html.map:
First, ensure you import the map function from Html:
import Html exposing (Html, map)
Update your main view function to wrap the sub-view output:
view : Model -> Html Msg view model = let -- Wrap view1's Html Msg1 into Html Msg using the M1 constructor v1 = map M1 (view1 model.model1) -- Repeat the same pattern for view2 if needed v2 = map M2 (view2 model.model2) in -- Combine your sub-views into the parent layout Html.div [] [ v1, v2 ]
Your sub-view remains unchanged—it still works with its own message type:
view1 : Model1 -> Html Msg1 view1 model = -- Example sub-view: a button that triggers Msg1a Html.button [ Html.Events.onClick Msg1a ] [ Html.text "Trigger Sub-component Action" ]
Matching in Update
Don’t forget to handle the wrapped messages in your parent update function, and also map any commands from the sub-component using Cmd.map:
update : Msg -> Model -> (Model, Cmd Msg) update msg model = case msg of M1 subMsg -> let -- Delegate to the sub-component's update function (updatedModel1, subCmd) = update1 subMsg model.model1 in ( { model | model1 = updatedModel1 }, Cmd.map M1 subCmd ) M2 subMsg -> -- Similar logic for Msg2 and model2 let (updatedModel2, subCmd) = update2 subMsg model.model2 in ( { model | model2 = updatedModel2 }, Cmd.map M2 subCmd )
This pattern keeps your components clean and decoupled, each managing their own state and messages, while seamlessly integrating into the parent application.
内容的提问来源于stack exchange,提问作者TPJ

