【问题标题】:Close antd popover and open a child antd modal in the same function关闭 antd popover 并在同一个函数中打开一个子 antd modal
【发布时间】:2022-01-15 08:43:22
【问题描述】:

我有一个 Antd 弹出框,通过单击其内容中的按钮,打开一个模式。 我想在模式打开时关闭弹出框。

当我尝试将弹出框可见性状态设置器作为道具传递给模态时,出现了问题。 modal 的状态和 popover 的向下传递的 prop 状态之间存在某种“冲突”:

Collision CodeSandbox example

我确实找到了一种解决方法 - 在父组件(弹出框)中创建模态状态变量并使用 props 将它们传递给模态:

Working CodeSandbox example

首先,您会注意到模态框并没有按预期关闭 - 没有很好的平滑动画将其最小化,它只是突然消失了。作为参考,你可以看看here,看看它关闭时的样子。

所以我的问题是 - 为什么会发生这种碰撞?有没有更好的办法解决?

谢谢!

【问题讨论】:

  • 这个解决方案怎么样?如果可以,请告诉我作为答案发布codesandbox.io/s/…
  • 因为modal来源于popover,以后被销毁,所以popup动画不起作用,我认为你必须将modal和popover的内容分开来防止这种情况发生
  • 这是一个很好的解决方案!但我的问题的另一部分仍未得到解答:为什么首先会发生这种“碰撞”?

标签: reactjs react-hooks antd react-props react-state


【解决方案1】:

发生这种冲突是因为在显示模态处理程序中,您将弹出框的可见性设置为 false 并将其隐藏,并且 ant-popover-hidden 类添加到它的 div 元素中,因此其中的任何内容都不会像模态一样显示,但是您显示模态但因为它父它看不到,所以我认为您必须将模式与弹出内容分开并将其放置在它们旁边的某个位置,如下所示:

const Test = () => {
  const [isSharePopoverVisible, setIsSharePopoverVisible] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const handlePopoverVisibleChange = () => {
    setIsSharePopoverVisible(!isSharePopoverVisible);
  };

  const handleOk = () => {
    setIsModalVisible(false);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const showModal = () => {
    setIsModalVisible(true);
    setIsSharePopoverVisible(false);
  };

  return (
    <>
      <Popover
        trigger="click"
        title="Test"
        visible={isSharePopoverVisible}
        onVisibleChange={handlePopoverVisibleChange}
        content={
          <Button type="primary" onClick={showModal}>
            Open Modal
          </Button>
        }
      >
        <Button>Test</Button>
      </Popover>
      <Modal
        title="Basic Modal"
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <p>Some contents...</p>
      </Modal>
    </>
  );
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-12
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 2019-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多