Elm中Maybe a→Svg Msg类型函数遇Nothing时的返回值问题
解决Elm中Maybe Block渲染为SVG的问题
嘿,我刚好碰到过类似的Elm SVG场景,给你几个靠谱的解决方案,不用修改函数签名就能搞定!
你的核心问题是:当prey为Nothing时,需要返回一个合法的Svg Msg类型,但Elm的svg库确实没有直接提供Svg.none这样的API。这里有两个简洁的替代方案:
方案1:使用空的<g>元素
最直接的方式是返回一个空的分组元素Svg.g [] [],它属于Svg Msg类型,渲染后不会产生任何可见内容,完全符合需求。修改后的代码如下:
type alias Block = {x:Int, y:Int} type alias Prey = Maybe Block renderPrey : Prey -> Svg Msg renderPrey prey = case prey of Just block -> Svg.rect [ Svg.x (String.fromInt block.x) , Svg.y (String.fromInt block.y) , Svg.width "20" -- 替换为你需要的尺寸 , Svg.height "20" , Svg.fill "orange" -- 示例样式,可自定义 ] [] Nothing -> Svg.g [] [] -- 空分组,无渲染内容
方案2:自定义svgNone复用函数
如果你觉得空g不够直观,可以封装一个复用的空元素函数,让代码可读性更好:
-- 自定义空SVG元素 svgNone : Svg msg svgNone = Svg.g [] [] type alias Block = {x:Int, y:Int} type alias Prey = Maybe Block renderPrey : Prey -> Svg Msg renderPrey prey = case prey of Just block -> Svg.rect [ Svg.x (String.fromInt block.x) , Svg.y (String.fromInt block.y) , Svg.width "20" , Svg.height "20" , Svg.fill "orange" ] [] Nothing -> svgNone
这两种方案都不需要修改函数签名,完美保持renderPrey : Prey -> Svg Msg的类型定义,同时在Nothing分支返回合法的空SVG元素,不会影响页面渲染。
内容的提问来源于stack exchange,提问作者C.S.Reddy Gadipally
相关产品推荐
相关产品推荐

