react-xarrows在水平滚动Div中箭头不随按钮移动的解决方案求助
解决react-xarrows在滚动容器中位置不更新的问题
问题原因
滚动容器时,按钮位置随滚动变化,但react-xarrows无法自动检测这种位置变更,导致箭头停留在初始渲染位置。需手动触发箭头位置的重新计算。
解决步骤
- 获取箭头更新函数:通过
useXarrowsHook获取更新函数,用于强制react-xarrows重新计算箭头位置。 - 监听滚动事件:给滚动容器添加滚动监听器,每次滚动时调用更新函数。
- 统一使用Xwrapper:将所有关联元素和箭头包裹在单个
Xwrapper中,确保react-xarrows能正确管理上下文。
修正后的代码
import React, { useRef, useEffect } from 'react'; import { Xarrow, Xwrapper, useXarrows } from 'react-xarrows'; const YourComponent = () => { const scrollRef = useRef(null); const updateXarrows = useXarrows(); // 获取箭头更新函数 // 绑定滚动事件监听 useEffect(() => { const scrollContainer = scrollRef.current; if (!scrollContainer) return; const handleScroll = () => { updateXarrows(); // 滚动时触发箭头位置更新 }; scrollContainer.addEventListener('scroll', handleScroll); return () => scrollContainer.removeEventListener('scroll', handleScroll); }, [updateXarrows]); return ( <div className="row w-100" style={{ overflowX: "auto" }} ref={scrollRef}> <Xwrapper> {/* 统一包裹所有需要连接的元素 */} <div style={{ display: "inline-block", textAlign: "center", whiteSpace: "nowrap", }} > {array.map((e, index) => { if (index + 1 < array.length) { return ( <React.Fragment key={index}> <button type="button" className="btn version-button" value={e} id={e} > {e} </button> <Xarrow start={e} end={array[index + 1]} color="black" path="smooth" headSize={3} dashness={true} strokeWidth={2} /> </React.Fragment> ); } else { return ( <button key={index} type="button" className="btn version-button" value={e} id={e} > {e} </button> ); } })} </div> </Xwrapper> </div> ); }; export default YourComponent;
关键说明
- useXarrows的正确使用:必须在组件顶层调用,返回的
updateXarrows函数能强制所有箭头重新计算位置,不能在事件回调中直接调用Hook。 - 滚动事件监听:通过
useEffect绑定和清理滚动监听器,避免内存泄漏,确保滚动动作触发箭头更新。 - Xwrapper的作用:单个
Xwrapper即可管理所有箭头的上下文,无需在循环中重复创建。 - 列表key属性:为循环元素添加唯一
key,符合React列表渲染规范,避免不必要的重渲染问题。
内容的提问来源于stack exchange,提问作者Shradha Tiwari
相关产品推荐
相关产品推荐

