[英]Scroll action in PureScript Halogen
我正在使用purescript-halogen,我想在捕获子组件的消息时滚动到div的底部。 但是,似乎没有Halogen中的滚动动作控制。 那么,我如何滚动到div的底部?
我认为的一个解决方案是,当事件发生时,调用其他,而不是Halogen,从Main处理。 我不确定这个解决方案是不是坏事。
设置滚动位置只需使用正常的DOM功能,以渲染节点为目标。
为此,您需要在HTML DSL中将ref
属性添加到要滚动的节点:
-- Define this in the same module as / in the `where` for a component
containerRef ∷ H.RefLabel
containerRef = H.RefLabel "container"
-- Use it with the `ref` property like so:
render =
HH.div
[ HP.ref containerRef ]
[ someContent ]
然后在组件的eval
中,您可以使用getHTMLElementRef
获取创建的实际DOM元素,然后更新其上的滚动位置:
eval (ScrollToBottom next) = do
ref ← H.getHTMLElementRef containerRef
for_ ref \el → H.liftEff do
scrollHeight ← DOM.scrollHeight el
offsetHeight ← DOM.offsetHeight el
let maxScroll ← scrollHeight - offsetHeight
DOM.setScrollTop maxScroll el
pure next
这里的片段是从一些类似的真实世界代码修改的,所以应该做的伎俩!
与https://stackoverflow.com/a/44543329/1685973基本相同的答案,但我很难找到不同的导入:
import Halogen as H
import Halogen.HTML as HH
import Data.Foldable (for_)
import DOM.HTML.Types (htmlElementToElement)
import DOM.Node.Element (scrollHeight, setScrollTop)
import DOM.HTML.HTMLElement (offsetHeight)
...
-- Define this in the same module as / in the `where` for a component
containerRef ∷ H.RefLabel
containerRef = H.RefLabel "container"
-- Use it with the `ref` property like so:
render =
HH.div
[ HP.ref containerRef ]
[ someContent ]
...
eval (ScrollToBottom next) = do
ref <- H.getHTMLElementRef containerRef
for_ ref $ \el -> H.liftEff $ do
let hel = htmlElementToElement el
sh <- scrollHeight hel
oh <- offsetHeight el
let maxScroll = sh - oh
setScrollTop maxScroll hel
pure next
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.