动态父元素

时间:2017-06-17 10:03:59

标签: haskell reflex

我有这段代码,它工作得非常好。它根据字段值在文本输入字段上切换一些样式。

numberInput :: (MonadWidget t m) => m (Dynamic t (Maybe Double))
numberInput = divClass "form-group" $ do
  let errorState = "style" =: "border-color: red"
      validState = "style" =: "border-color: green"
  rec n <- textInput $ def & textInputConfig_inputType .~ "number"
                           & textInputConfig_initialValue .~ "0"
                           & textInputConfig_attributes .~ attrs
      let result = fmap (readMay . unpack) $ _textInput_value n
          attrs  = fmap (maybe errorState (const validState)) result
  return result

我遇到了一些使父元素动态化的问题。我想在文本输入的父元素上切换样式。我想写一些像失败的东西!

numberInput :: (MonadWidget t m) => m (Dynamic t (Maybe Double))
numberInput = do
  rec 
      dynAttrs <- -- reference to textInput
      elDynAttr "div" dynAttrs $ do
        n <- textInput $ def & textInputConfig_inputType .~ "number"
                       & textInputConfig_initialValue .~ "0"
        ...

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

这是一个小程序,其中父元素的属性(对齐或左对齐)取决于子元素的状态:

{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecursiveDo #-}
import Reflex.Dom
import qualified Data.Text as T
import Safe

main :: IO ()
main = mainWidget bodyElement 

bodyElement :: MonadWidget t m => m ()
bodyElement =  el "div" $ do
    el "h2" $ text "Dynamic parent element"
    numberInput
    return ()

numberInput :: (MonadWidget t m) => m (Dynamic t (Maybe Double))
numberInput =  do
    rec
       let errorState = ("align" :: T.Text) =: "right"
           validState = "align" =: "left"
       let result = fmap (readMay . T.unpack) $ _textInput_value n 
           attrs  = fmap (maybe errorState (const validState)) result
       n <- elDynAttr "div" attrs $ do
          n1 <- textInput $ def & textInputConfig_inputType .~ "number"
                                & textInputConfig_initialValue .~ "0"

          text "Some additional control"
          return n1
    return result

当用户 user2407038 提及时,我们必须将数字文本元素从内部范围返回到外部范围。然后我们可以使用recursive do来访问我们稍后在程序中定义的元素。

只要在数字字段中输入一个字母,它就会跳到右边。