1

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

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"
        ...

感谢您的帮助!

4

1 回答 1

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 所提到的,我们必须将数字文本元素从内部范围返回到外部范围。然后我们可以使用递归do来访问我们稍后在程序中定义的元素。

只要您在数字字段中键入一个字母,它就会跳到右侧。

于 2017-06-21T15:53:59.083 回答