当在具有唯一键的表中的内联按钮上使用时,“材料UI弹出框"被投到左上方 [英] Material UI Popover is thrown to the top left when used on an inline button in a table with a unique key

查看:36
本文介绍了当在具有唯一键的表中的内联按钮上使用时,“材料UI弹出框"被投到左上方的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用shortid或任何其他唯一的uid生成器时,我遇到了一些问题.当我将 shortid.generate()用作表中的键时,我的 Material UI Popover 的锚点被扔到其默认位置,而不是出现在按钮所在的位置

I'm having some issues when using shortid or any other unique uid generator. The moment I use shortid.generate() as key in a table, the anchor point of my Material UI Popover is thrown to its default position rather than appearing where the button is.

这是一个沙箱!-尝试删除/添加回shortid.generate()从第72行开始.

Here's a sandbox! - try removing/adding back shortid.generate() from line 72.

我什至从lodash尝试了 uniqueId ,并且发生了相同的事情-使用键确实将对话框呈现在正确的位置.我什至更改了Material UI/React的版本,什么也没发生.

I even tried uniqueId from lodash and the same thing happens - not using a key does render the dialog on the right place though. I even changed versions of Material UI/React and nothing happened.

有什么想法吗?

谢谢!

编辑-我通常使用 item.uid 作为键,因为我总是从服务中获取项目,但是如果我只是创建对象,则 item.uid undefined -我直到现在要做的是在创建对象时设置 item.uid = shortid.generate()(临时uid),然后只需保持< TableRow key = {item.uid}> 不变.但是然后我必须先删除临时uid,然后再保存对象.

EDIT - I usually use item.uid as key since I always fetch items from a service, but if I just created the object, item.uid is undefined - what I did until now was to set item.uid = shortid.generate() (a temporary uid) when I create the object and then just leave <TableRow key={item.uid}> as is. But then I have to remove the temporary uid before I save the object.

推荐答案

绝对不要使用随机ID作为键(至少不要使用在渲染期间生成的随机ID ).

You should never use random ids as keys (at least not random ids generated during render).

当您的状态更改时(例如,由于 handleClick 导致),您的表行将全部使用新键重新呈现.这意味着将代替所有简单的重新渲染,而是卸载所有表行并安装新的DOM元素.您状态中的 anchorEl 将指向已从 DOM 中删除的元素,因此无法确定其位置.

When your state changes (e.g. due to handleClick) your table rows will all be re-rendered with new keys. This means that instead of a simple re-render, all of the table rows will be unmounted and new DOM elements mounted. The anchorEl in your state will point at an element that has been removed from the DOM, so its position cannot be determined.

如果您没有与数据相关的唯一键,则只需使用索引作为键,这样它就至少可以在所有渲染中保持稳定(只要您不添加/删除行).另一种选择是在创建数据时而不是在渲染过程中生成唯一ID.

If you don’t have unique keys related to your data, then just use an index as a key so that it is at least stable across renders (so long as you aren’t adding/removing rows). Another option would be to generate the unique ids when creating your data instead of during rendering.

这篇关于当在具有唯一键的表中的内联按钮上使用时,“材料UI弹出框"被投到左上方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆