我如何在Reflex Dynamic内部分配值? [英] How can I branch on the value inside a Reflex Dynamic?

查看:123
本文介绍了我如何在Reflex Dynamic内部分配值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在最简单的情况下,假设我有一个 Dynamic t Bool ,并且当这个值为true时,我想要一个空的div存在,当这个值是假如我有一个动态t(MyA MyB),我不希望有任何dom元素。 p

,并且我有函数知道如何给定一个动态t MyA 或者一个动态t MyB ,如何调用适当的函数来渲染?

解决方案

如果您需要切换小部件,您可能需要一个

  dyn :: MonadWidget tm =>动态t(m a) - > m(事件ta)来源



  widgetHold :: MonadWidget tm => m a  - >事件t(m a) - > m(动态ta)

既然你提到你手头有Dynamic,我们会使用 dyn

  app = do 
转换< ; - 按钮交替!
标志< - foldDyn($)False(不是< $转换) - 只是为了让一些Dynamic t Bool
let w = myWidget< $> flag
void $ dyn w

myWidget :: MonadWidget t m =>布尔 - > m()
myWidget False =空白
myWidget True = eldiv$ blank



基本规则是,由于Reflex的高阶特性,如果你想换出一些东西,你需要有一个Event / Dynamic来产生一个widget作为一个值。这就是为什么 dyn 动态t(ma)作为参数的原因(适当地, widgetHold 需要事件t(ma)。这就是为什么我们映射了 Dynamic t Bool 有一个动态的,我们的小部件建设行动作为一个价值。



值得一提的是,dynamic / widgetHold都没有虚拟dom / diffing来加速渲染。你可以更清楚地知道什么更新(动态/事件t文本可以直接影响节点文本,而不需要重新渲染整个节点),你应该利用这一点,否则大部分页面将被交换,性能受到影响。

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.

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?

解决方案

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:

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. That's why dyn takes Dynamic t (m a) as its parameter (and appropriately, widgetHold takes Event t (m a). And that's why we've mapped over Dynamic t Bool to have a dynamic that has our widget building action as a value.

It's worth mentioning, that neither dynamic/widgetHold does virtual dom/diffing to speed the rendering. 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.

这篇关于我如何在Reflex Dynamic内部分配值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆