Antd 弹出窗口根据执行操作的顺序以两种不同的宽度打开

Antd popover opening in two diffrent widths depending on the order in which the actions are performed

sorry if the title is confusing, I don't know how else to put it into words.

我目前正在学习 React 并制作 this application using antd UI components。我有这个功能,我可以在购物车中添加和删除商品。

我正在使用弹出框来列出添加到购物车中的购物车商品。弹出窗口以两种不同的宽度打开,具体取决于我在应用程序中执行操作的顺序。

如果我在将任何东西添加到购物车之前打开购物车,购物车将在狭窄的容器中打开,而购物车中没有任何内容。如果我在那之后将任何东西添加到购物车。然后购物车保持狭窄并且不适合所有东西。

现在重新加载页面

在打开弹出框之前将商品添加到购物车。现在你可以看到弹出窗口更宽了,可以正确地容纳所有内容。

我该如何解决这个问题?

可重现的例子:Code Sandbox link

github: https://github.com/nijeesh4all/reactShopping

感谢 reddit 上的 u/jnforja

<Popover      
placement="bottom"      
title="YOUR CART"      
content={listContent}      
trigger="click"      
key={this.boughtItems() > 0}>

将项目添加到弹出窗口后更改密钥似乎可以解决问题。

In my opinion, what is happening should be considered a bug on the popover component. Before clicking for the first time on the cart, the popover element doesn't exist in the DOM. After user's first click, the popover DOM element will be created and positioned in the screen taking into account the current dimensions of the content. The created DOM element will be reused even when the content changes. However, when the content changes, the dimensions and positioning are not correctly recalculated (The reason why I'm not sure). So when we change from an empty list to a list with at least one item, the result is what we've seen.

One solution to fix this, is to tell React not to reuse the dom element it has created. We can do that through the key attribute. Since, from what I've seen, we can re-use the popover dom element for situations where we have 1 or more elements, I made the popover key to be the same in those situations. Thus, the expression this.boughtItems() > 0

If you want to know more about the key property, you can read this part of React's documentation.

This is self-promotion, but this article I wrote about using the key attribute to animate images on change might also help you understand how this key attribute thing works.

我们可以使用 overlayStyle 属性 来给出固定的宽度和高度,如下所示:

<Popover
  visible={true}
  overlayStyle={{
    width: "20vw"
  }}
  content={<div>HELLO</div>}
>
  hello
</Popover>

可以在antd的tooltip中使用属性overlayClassName。您可以参考下面的link: https://ant.design/components/tooltip/#API

<Popover
   overlayClassName="wrapper-notify"
   placement="bottomRight"
   title={<span>Thông báo</span>}
   content={}
   trigger="click"
>

.ant-popover.wrapper-notify {
  position: fixed;
  width: 300px;
}