我有一个模态窗口,可以在其中显示不同的组件。每个组件都有其自己的更新程序和消息,但是我想在它们之间共享一个关闭按钮。
因此,我不能直接从我的孩子那里叫“ CloseModal”-Elm不允许我给其他人打电话。我有什么选择?
我以为我可以称之为“ Modal.Update.update Modal.Messages.CloseModal”,但是在我的组件内部,我只有一个状态块。所以这不是一个选择。
然后,我找到了一种将消息从父母传递给孩子的方法,但这并不能帮助我以其他方式传递消息。或兄弟姐妹。
简而言之,您不能将消息直接从子级传递到父级或同级。
Elm Architecture实现了单向消息传递,换句话说,在子组件接收到消息之前,您的父组件始终知道子组件的消息。
我已经做了一个简单的亲子沟通示例,将其嵌入答案中太大了,因此在这里我仅会指出关键点。
子组件定义了一组消息:
type Msg
= Update Model
| Focus
| Blur
在此update
函数中,我们忽略用于父组件的消息。
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的update
功能中,我们可以对所需的消息进行模式匹配并对它们做出反应。
其余消息将通过默认分支。
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
)
上面的示例总结了儿童-父母与兄弟姐妹之间的通信。您可以根据需要以递归方式运行更新功能,并向任何组件发送任何消息。
update
功能发送信息Cmd.Extra公开了用于发送消息的功能。
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model ->
(model, message SomeMessage)
PS:翻译模式示例在我的待办事项上,如果您想让我用它来更新答案,请发表评论。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句