如何在Elm应用中同时使用Html.Styled与Navigation包的program函数?
嗨,刚好我之前也碰到过这个Elm包兼容的问题,给你捋清楚怎么解决~
首先明确一点:Elm应用只能有一个入口program函数,所以没法同时用两个包的program。不过别担心,我们可以把两个包的功能完美结合起来,核心思路是用Navigation的program作为应用入口,然后把Html.Styled生成的视图转换成标准Html视图就行。
核心方法:将Styled视图转为标准Html
Html.Styled专门提供了toUnstyled函数,能把它生成的Html.Styled.Html转换成Elm标准的Html,这样就能和Navigation的program无缝兼容了。
代码示例
给你一个简化版的完整代码参考,你可以照着调整成自己的应用逻辑:
-- 导入所需模块 import Navigation exposing (Location, program) import Html.Styled exposing (Html, div, text, toUnstyled) import Html.Styled.Attributes exposing (css) import Css exposing (color, px, fontSize, padding) -- 定义应用模型 type alias Model = { location : Location -- 这里添加你的其他模型字段 } -- 定义消息类型 type Msg = OnLocationChange Location -- 这里添加你的其他消息类型 -- 初始化函数 init : Location -> (Model, Cmd Msg) init initialLocation = ( { location = initialLocation }, Cmd.none ) -- 更新函数 update : Msg -> Model -> (Model, Cmd Msg) update msg model = case msg of OnLocationChange newLoc -> ( { model | location = newLoc }, Cmd.none ) -- 这里处理你的其他消息逻辑 -- 视图函数:关键是最后用toUnstyled转换 view : Model -> Html Msg view model = div [ css [ color (Css.hex "#2c3e50") , fontSize (px 18) , padding (px 20) ] ] [ text ("当前访问路径:" ++ model.location.pathname) ] |> toUnstyled -- 应用入口:使用Navigation的program main : Program Never Model Msg main = program OnLocationChange { init = init , update = update , view = view , subscriptions = \_ -> Sub.none }
额外说明(针对Elm 0.19+)
如果你的Elm版本是0.19或更高,Navigation包的功能已经被整合到官方的Browser模块里了,推荐用Browser.application来处理路由,原理完全一样——还是用toUnstyled把Styled视图转成标准视图就行,只是入口函数的写法略有调整,你可以根据官方文档调整代码结构。
这样你就能同时用上Html.Styled的样式能力和Navigation的路由功能啦!
内容的提问来源于stack exchange,提问作者fladrif
相关产品推荐
相关产品推荐

