订购的试剂成分按其计算的大小跨度 [英] reagent component that orders spans by their computed sizes
问题描述
我正在寻找一种设计试剂组件的方法,该组件列出按其实际(计算的)宽度排序的单词,这些单词在浏览器中呈现时将具有的宽度. (不是字符数).
I'm looking for a way to design a reagent component, which lists words sorted by their real(computed) widths, which they would have when rendered in the browser. (not the number of characters).
html元素的实际宽度可以通过JavaScript方法offsetWidth
确定.但是,看起来要获得结果,必须将元素附加到DOM中的某个位置.
The real width of an html element can be determined by the JavaScript method offsetWidth
. However, it looks that in order to get a result, the element must be appended somewhere in the DOM.
因此,必须通过以下方式解决此问题
So this could be imperatively solved by
- 创建一个不可见的临时容器元素
- 附加一些包含单词的跨度
- 按它们的offsetWidth排序
- 相应地重新添加它们
什么是反应/试剂方法?
What would be the React/Reagent approach to it?
推荐答案
一种方法是使用:ref
函数
(defn sorted-by-width []
(let [ss (reagent/atom {"the" nil
"quick" nil
"brown" nil
"fox" nil})]
(fn a-sorted-by-width []
[:ul
(for [[s width] (sort-by val @ss)]
^{:key s}
[:li
[:span
{:ref (fn text-ref [elem]
(when elem
(swap! ss assoc s (.-width (.getBoundingClientRect elem)))))
:visibility (if width "visible" "hidden")}
s]])])))
ref函数可以记录有关元素的信息.
The ref function can record information about the element.
这篇关于订购的试剂成分按其计算的大小跨度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!