英文:
Control Popover antd by button but still keep default behavior
问题
我想使用按钮来控制 Popover Antd,这意味着我可以通过点击按钮来显示和隐藏弹出框。此外,我希望保留其默认行为,所以当我点击内容时,弹出框会显示,并在我点击它之外的地方时隐藏。非常感谢。
英文:
I want to control the Popover Antd using a button, which means I can show and hide the popover by clicking the button. Additionally, I want to retain its default behavior, so when I click on the content, the popover will show up and be hidden when I click outside of it. Thank you so much.
答案1
得分: 1
要控制Ant Design(Antd)中的Popover组件使用按钮,您可以使用Popover的visible
属性,根据按钮点击的状态来有条件地显示或隐藏它。此外,为了保留在点击内容时显示Popover并在点击外部时隐藏它的默认行为,您可以使用Popover的trigger
属性,其值为"click"。
App.jsx
import React, { useState } from 'react';
import { Button, Popover } from 'antd';
const App = () => {
const [visible, setVisible] = useState(false);
// 函数用于切换Popover的可见性
const handleTogglePopover = () => {
setVisible(!visible);
};
// 在Popover内显示的内容
const content = (
<div>
<p>This is the content of the Popover</p>
<p>Clicking inside the Popover won't hide it.</p>
</div>
);
return (
<div>
<Popover
content={content}
visible={visible}
trigger="click" // 点击内容时显示Popover
onVisibleChange={(visible) => setVisible(visible)} // 当可见性变化时更新状态
>
<Button onClick={handleTogglePopover}>Toggle Popover</Button>
</Popover>
</div>
);
};
export default App;
希望这对您有所帮助!
英文:
To control the Popover component in Ant Design (Antd) using a button, you can use the visible
prop of the Popover to conditionally show or hide it based on the state of a button click. Additionally, to retain the default behavior of showing the Popover when clicking on the content and hiding it when clicking outside, you can use the trigger
prop with the value "click" for the Popover.
App.jsx
<!-- language: lang-js -->
import React, { useState } from 'react';
import { Button, Popover } from 'antd';
const App = () => {
const [visible, setVisible] = useState(false);
// Function to toggle the visibility of the Popover
const handleTogglePopover = () => {
setVisible(!visible);
};
// Content to be displayed inside the Popover
const content = (
<div>
<p>This is the content of the Popover</p>
<p>Clicking inside the Popover won't hide it.</p>
</div>
);
return (
<div>
<Popover
content={content}
visible={visible}
trigger="click" // Show the Popover on click of the content
onVisibleChange={(visible) => setVisible(visible)} // Update the state when the visibility changes
>
<Button onClick={handleTogglePopover}>Toggle Popover</Button>
</Popover>
</div>
);
};
export default App;
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论