gpt4 book ai didi

elm - 如何从 Elm 组件中调用父消息?

转载 作者:行者123 更新时间:2023-12-02 14:51:13 25 4
gpt4 key购买 nike

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

因此我无法直接从我的 child 那里调用“CloseModal”——Elm 不允许我调用其他人的消息。我有什么选择?

<小时/>

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

然后我找到了一种将消息从父级传递给子级的方法,但这并不能帮助我以其他方式传递消息。或者 sibling 。

最佳答案

简而言之,您无法将消息直接从子级传递给父级或兄弟级。

Elm 架构实现了单向消息传递,换句话说,在子组件接收消息之前,您的父组件始终知道子组件的消息。

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

子级

子组件定义了 set of Messages :

type Msg
= Update Model
| Focus
| Blur

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

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 )

父级

在父级的 update 函数中,我们可以对所需消息进行模式匹配并对它们使用react。

其余消息将通过 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 和 sibling 的沟通。您可以根据需要对发送给任何组件的任何消息递归地运行更新函数。

从 child 的更新功能发送消息

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

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

PS:翻译模式示例位于我的待办事项中,如果您希望我用它更新答案,请发表评论。

关于elm - 如何从 Elm 组件中调用父消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38827491/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com