这是一个简短的独立示例,它使用reflex-dom进行您描述的红色/蓝色切换。这是epsilonhalbe包含在您之前问题的答案中的代码的修改版本。
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-} -- allows for local type declarations.
import Reflex
import Reflex.Dom
import Data.Text (Text, pack)
import Data.Map (Map)
import Data.Time.Clock (getCurrentTime)
import Control.Monad.Trans (liftIO)
webPage :: MonadWidget t m => m ()
webPage = do
-- ticker Event fires once per second.
ticker :: Event t TickInfo <- tickLossy 1.0 =<< liftIO getCurrentTime
-- counter Dynamic increases by one every second.
counter :: Dynamic t Int <- foldDyn (\_ n -> n+1) 0 ticker
-- function to map from integer to red or blue style.
let chooseColor :: Int -> (Map Text Text)
chooseColor n = "style" =: pack ("color: " ++ if (n `mod` 2) == 0 then "red" else "blue")
-- redBlueStyle Dynamic changes each second.
let redBlueStyle :: Dynamic t (Map Text Text)
redBlueStyle = fmap chooseColor counter
-- insert an h1 elemnt.
el "h1" $ text "Hello World!"
-- insert a paragraph with Dynamic red blue style.
elDynAttr "p" redBlueStyle $ text "This is my test document"
return ()
css = "h1 {font-family: Helvetica;} p {font-family: Helvetica;}"
main :: IO ()
main = mainWidgetWithCss css webPage
当然,reflex-dom(连同 reflex)是一个比 ghcjs-dom 更高级别的库,它有自己的一组概念(事件、动态、行为等),您需要熟悉这些概念。
该示例通过创建一个动态地图来工作,该地图指定每秒从红色到蓝色交替的样式,并使用该动态地图来设置元素的样式。
为清楚起见,此示例包含一些并非严格要求的类型声明。
这个项目:https ://github.com/dc25/stackOverflow__how-to-change-h1-tags-with-ghcjs-dom包含上面的代码。这是一个基于浏览器的演示的链接:https ://dc25.github.io/stackOverflow__how-to-change-h1-tags-with-ghcjs-dom/