Open Parmerlee opened 1 month ago
看看 popRef
的创建方式
https://github.com/ant-design/ant-design-mobile/blob/master/src/components/popover/popover.tsx#L198 通过show()打开时触发了useClickAway了,去掉props中的trigger即可,但是这样就只能通过hide()关闭了。
当组件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
e.stopPropagation(); // 阻止冒泡事件
这个可以了
当组件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
这样也可以,但是可能不是每个使用者都知道要加上这行代码才能生效。。。
还可以使用定时器,先让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>
);
}
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?
如图所示,通过menu 图片打开Popover 一切正常,但是line1 的div中通过ref打开pop时,页面没有任何反应。
Relevant log output