【发布时间】:2016-02-21 18:52:11
【问题描述】:
我在网上的任何地方都找不到一个例子来回答这个问题:父组件如何响应来自子模块的不同操作? 考虑一个带有提交按钮的简单聊天消息输入:
// 子组件:带有提交按钮的文本输入
type Action
= InputChanged String
| MessageSent String
view : Signal.Address Action -> Model -> Html
view addr model =
div []
[ input
[ type' "text"
, value model.content
, on "input" targetValue (\val -> Signal.message addr (InputChanged val))
]
[]
, button
[ type' "submit"
, onClick addr (MessageSent model.content)
]
[ text "Send" ]
]
持有该输入框的父组件如何响应该输入框可能出现的两个动作?传统的“路过”是这样的:
// 父组件,持有帖子列表和子组件
-- update
type Action
= MessageBoxAction MessageBox.Action
update : Action -> Model -> Model
update act model =
case act of
MessageBoxAction msg ->
{ model |
currentMessage = MessageBox.update msg model.currentMessage
}
-- view
view : Signal.Address Action -> Model -> Html
view addr model =
div []
[ MessageBox.view (Signal.forwardTo addr MessageBoxAction) model.currentMessage ]
我想要做的是捕获来自该子组件的消息,并在正常的“刚刚通过”之外对其进行响应。像这样的:
case act of
MessageBoxSubmit msg ->
let updatedMessage = MessageBox.update msg model.currentMessage
newPost = Posts.update msg model.posts
in
{ model |
posts = model.posts :: [ newPost ]
, currentMessage = updatedMessage
}
但我不知道该怎么做,特别是因为在将地址转发给孩子时,您没有机会提供多个地址...
MessageBox.view (Signal.forwardTo addr MessageBoxAction) model.currentMessage
【问题讨论】:
-
使用带有效果的 StartApp 时,我会向子组件更新发送地址。如此处所述elm-tutorial.org/showing_errors/players_update.html 这可能对您有用
标签: elm