ant-design / ant-design-mobile

Essential UI blocks for building mobile web apps.
https://mobile.ant.design
MIT License
11.64k stars 2.4k forks source link

Popover 使用ref打开失败 #6731

Open Parmerlee opened 1 month ago

Parmerlee commented 1 month ago

Version of antd-mobile

5.37.1

Operating system and its version

iOS, Android, Others

Browser and its version

所有手机上均不生效

Sandbox to reproduce

No response

What happened?

image 如图所示,通过menu 图片打开Popover 一切正常,但是line1 的div中通过ref打开pop时,页面没有任何反应。

Relevant log output

1123123123
tylerrrkd commented 1 month ago

看看 popRef 的创建方式

DaJianWu commented 1 month ago

https://github.com/ant-design/ant-design-mobile/blob/master/src/components/popover/popover.tsx#L198 通过show()打开时触发了useClickAway了,去掉props中的trigger即可,但是这样就只能通过hide()关闭了。

xiaoyao96 commented 1 month ago

当组件Popover指定trigger='click'后,点击该Popover以外的元素,预期会隐藏该Popover(点击事件冒泡)。 解决方案:使用e.stopPropagation()来阻止冒泡事件,然后使用ref来控制其显示。

function App() {
  const ref = React.createRef();
  return (
    <div className="App">
      <h1>Popover With trigger='click'</h1>
      <Popover
        ref={ref}
        content="Hello World"
        trigger="click"
        placement="right"
      >
        <Button>点我</Button>
      </Popover>
      <br />
      <Button
        onClick={(e) => {
          e.stopPropagation(); // 阻止冒泡事件
          ref.current.show();
        }}
      >
        点我通过ref控制
      </Button>
    </div>
  );
}

demo地址: https://codesandbox.io/p/sandbox/naughty-darkness-lvhc3q?file=%2Fsrc%2FApp.tsx%3A19%2C26

Parmerlee commented 1 month ago
 e.stopPropagation(); // 阻止冒泡事件

这个可以了

DaJianWu commented 1 month ago

当组件Popover指定trigger='click'后,点击该Popover以外的元素,预期会隐藏该Popover(点击事件冒泡)。 解决方案:使用e.stopPropagation()来阻止冒泡事件,然后使用ref来控制其显示。

function App() {
  const ref = React.createRef();
  return (
    <div className="App">
      <h1>Popover With trigger='click'</h1>
      <Popover
        ref={ref}
        content="Hello World"
        trigger="click"
        placement="right"
      >
        <Button>点我</Button>
      </Popover>
      <br />
      <Button
        onClick={(e) => {
          e.stopPropagation(); // 阻止冒泡事件
          ref.current.show();
        }}
      >
        点我通过ref控制
      </Button>
    </div>
  );
}

demo地址: https://codesandbox.io/p/sandbox/naughty-darkness-lvhc3q?file=%2Fsrc%2FApp.tsx%3A19%2C26

这样也可以,但是可能不是每个使用者都知道要加上这行代码才能生效。。。

xiaoyao96 commented 1 month ago

还可以使用定时器,先让Povover触发自身关闭完成后,再使用ref.current.show()来展示。

function App() {
  const ref = React.createRef();
  return (
    <div className="App">
      <h1>Popover With trigger='click'</h1>
      <Popover
        ref={ref}
        content="Hello World"
        trigger="click"
        placement="right"
      >
        <Button>点我</Button>
      </Popover>
      <br />
      <Button
        onClick={(e) => {
          setTimeout(() => { // 使用定时器
            ref.current.show();
          });
        }}
      >
        点我通过ref控制
      </Button>
    </div>
  );
}