我在项目中使用Material-UI和react-window。我的问题是,当Material-UI菜单组件位于react- window虚拟列表中时,material- ui菜单组件不会锚定到该元素。菜单将显示在屏幕的左上角,而不是固定在打开菜单的按钮上。在非虚拟化列表中使用它们时,它会按预期工作。菜单正确锚定在打开它的按钮上。
这是一个示例沙箱。沙盒非常特定于我如何使用相关组件。
关于如何解决此问题的任何指导?
这是沙盒的修改后的版本,可解决此问题:
这是您在中的初始代码BigList:
BigList
const BigList = props => { const { height, ...others } = props; const importantData = Array(101 - 1) .fill() .map((_, idx) => 0 + idx); const rows = ({ index, style }) => ( <FancyListItem index={index} styles={style} text="window'd (virtual): " {...others} /> ); return ( <FixedSizeList height={height} itemCount={importantData.length} itemSize={46} outerElementType={List} > {rows} </FixedSizeList> ); };
我将其更改为以下内容:
const Row = ({ data, index, style }) => { return ( <FancyListItem index={index} styles={style} text="window'd (virtual): " {...data} /> ); }; const BigList = props => { const { height, ...others } = props; const importantData = Array(101 - 1) .fill() .map((_, idx) => 0 + idx); return ( <FixedSizeList height={height} itemCount={importantData.length} itemSize={46} outerElementType={List} itemData={others} > {Row} </FixedSizeList> ); };
重要的区别在于,Row现在是一致的组件类型,而不是每次渲染时都重新定义BigList。使用您的初始代码,每次渲染都会导致重新安装BigList所有FancyListItem元素,而不仅仅是重新渲染,因为围绕它的表示“行”类型的函数是每次渲染时的新函数BigList。这样的效果是,在尝试确定锚点元素的位置时,Menu不再将要传递的锚元素装入,Menu并且anchorEl.getBoundingClientRect()提供的x,y位置为0,0。
Row
FancyListItem
Menu
您会在react-window文档(https://react-window.now.sh/#/examples/list/fixed- size)中注意到该Row组件是在组件外部定义的,Example类似于代码的固定版本现在已结构化。
Example