简体   繁体   English

如何在Reflex Dynamic内的值上进行分支?

[英]How can I branch on the value inside a Reflex Dynamic?

in the simplest case, say I have a Dynamic t Bool , and when the value is true, I want a single empty div to exist, and when the value is false, I don't want there to be any dom element. 在最简单的情况下,假设我有一个Dynamic t Bool ,并且当值为true时,我想要一个空的div存在,而当值为false时,我不想有任何dom元素。

slightly more generally, if I have a Dynamic t (Either MyA MyB) , and I have functions that know how to render given a Dynamic t MyA or a Dynamic t MyB , how to I call the appropriate function to render? 一般而言,如果我有一个Dynamic t (Either MyA MyB) ,并且我的函数知道如何在给定Dynamic t MyADynamic t MyB的情况下进行渲染,那么我该如何调用适当的函数进行渲染呢?

If you need to switch the widget you probably need one of: 如果您需要切换小部件,则可能需要以下之一:

dyn :: MonadWidget t m => Dynamic t (m a) -> m (Event t a) Source

or 要么

widgetHold :: MonadWidget t m => m a -> Event t (m a) -> m (Dynamic t a)

Since you've mentioned you've got Dynamic at hand, we're gonna use dyn : 既然您已经提到了Dynamic,那么我们将使用dyn

app = do
  switched <- button "Alternate!"
  flag <- foldDyn ($) False (not <$ switched) -- just to have some Dynamic t Bool
  let w = myWidget <$> flag
  void $ dyn w

myWidget :: MonadWidget t m => Bool -> m ()
myWidget False = blank
myWidget True = el "div" $ blank

The basic rule is that, due to the higer-order nature of Reflex, if you want to swap-out something, you need to have Event/Dynamic that yields a widget as a value. 基本规则是,由于Reflex的高阶性质,如果要换出某些东西,则需要具有将小部件作为值产生的Event / Dynamic。 That's why dyn takes Dynamic t (ma) as its parameter (and appropriately, widgetHold takes Event t (ma) . And that's why we've mapped over Dynamic t Bool to have a dynamic that has our widget building action as a value. 这就是dynDynamic t (ma)作为其参数的原因(适当地, widgetHold采用Event t (ma) ,这就是为什么我们在Dynamic t Bool上映射了一个具有将小部件构建动作作为值的动态的原因。

It's worth mentioning, that neither dynamic/widgetHold does virtual dom/diffing to speed the rendering. 值得一提的是,dynamic / widgetHold都不使用虚拟dom / diff来加快渲染速度。 With reflex you can be more explicit about what updates what (a Dynamic/Event t Text can affect node text directly, without rerendering whole node) and you should take advantage of that. 使用反射功能,您可以更清楚地知道哪些内容会更新内容(动态/事件文本可以直接影响节点文本,而无需重新渲染整个节点),您应该充分利用这一点。 If not then large portions of page will be swapped and it can yield significant performance hit. 如果不是这样,则页面的大部分将被交换,这可能会导致明显的性能下降。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM