我在一个项目中使用Material-UI和react-window。我的问题是,material-ui菜单组件不能锚定到在react-window虚拟化列表中提供的元素。菜单将出现在屏幕的左上角,而不是固定在打开它的按钮上。当在非虚拟化列表中使用它时,它会按预期工作。菜单正确地固定在打开它的按钮上。
Here's an example sandbox。沙箱对于我如何使用有问题的组件是非常具体的。
有什么关于我如何解决这个问题的指导吗?
发布于 2019-03-17 10:01:28
这里是你的沙箱的一个修改版本,可以解决这个问题:
以下是您在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元素,而不仅仅是重新呈现,因为它周围表示"row“类型的函数是每次呈现BigList时的一个新函数。这样做的一个效果是,当Menu尝试确定锚点元素的位置时,传递给Menu的锚点元素不再被挂载,而anchorEl.getBoundingClientRect()提供的x,y位置为0,0。
您会注意到,在react-window文档(https://react-window.now.sh/#/examples/list/fixed-size)中,Row组件是在Example组件之外定义的,类似于代码的修复版本现在的结构。
发布于 2019-12-12 21:47:41
Ryan感谢你的回答!这对我很有帮助!
还有另一种解决方案:将父组件定义为类组件(而不是功能组件)。
我的问题是,我是这样调用'Rows‘函数的:
<FixedSizeList
height={height}
itemCount={nodes.length}
itemSize={50}
width={width}
overscanCount={10}
>
{({ index, style }) => this.renderListItem(nodes[index], style)}
</FixedSizeList>修复方法与Ryan的建议类似:
render() {
...
return <FixedSizeList
height={height}
itemCount={nodes.length}
itemSize={50}
width={width}
overscanCount={10}
itemData={nodes}
>
{this.renderListItem}
</FixedSizeList>
}
renderListItem = ({data,index, style}) => {
...
}我使用了itemData属性来访问renderListItem函数内部的nodes数组
https://stackoverflow.com/questions/55192935
复制相似问题