[英]How to scroll a section to the top in Chakra Modal?
this is what I am trying to do这就是我想要做的
Box
that contains NutrientFilterOptions
.例如,单击“所有营养素”,模态应该打开,顶部的内容应该是包含NutrientFilterOptions
的Box
。My attempt is available at https://codesandbox.io/s/modest-edison-wz8qr?file=/src/App.tsx我的尝试可在https://codesandbox.io/s/modest-edison-wz8qr?file=/src/App.tsx 获得
What happens now?现在会发生什么?
Note: At this time, the code is only connected using ref
for Nutrients.注意:此时代码仅使用ref
for Nutrients 连接。
Any help in educating me how I can achieve my goal is greatly appreciated.在教育我如何实现我的目标方面的任何帮助都非常感谢。
Thank you谢谢
I have never seen chakra-ui so please excuse me for not completely solving this problem我从未见过chakra-ui,所以请原谅我没有完全解决这个问题
I managed to get the desired list to scroll into view with this modification to NutrientFilterOptions.tsx通过对 NutrientFilterOptions.tsx 的修改,我设法获得了想要滚动到视图中的列表
export const NutrientFilterOptions = () => {
useEffect(() => {
const ele = document.querySelector("#myNutFilter");
if (ele) ele.scrollIntoView();
}, []);
return (
<div id="myNutFilter">
What I am doing is giving the element an id instead of using useRef
, although useRef may be ideal in this situation.我正在做的是给元素一个 id 而不是使用useRef
,尽管在这种情况下 useRef 可能是理想的。
I am using useEffect
because I want the code to execute after the component renders.我使用useEffect
是因为我希望代码在组件呈现后执行。
After the component renders I have vanilla js to first check that the element exists (isShown) then I scroll it into view if it does exist.组件呈现后,我使用 vanilla js 首先检查元素是否存在(isShown),然后将其滚动到视图中(如果确实存在)。
I would like to add that this does not check how the list was initially shown.我想补充一点,这不会检查列表最初是如何显示的。 You would need a state that keeps track of what opened the options menu, and only scroll if that the source was correct.您需要一个状态来跟踪打开选项菜单的内容,并且只有在来源正确时才滚动。 I would use prop drilling or redux to handle the source of options opening.我会使用道具钻孔或 redux 来处理选项打开的来源。
hopefully that helps!希望有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.