Antd 的 Popcomfirm 打开之后,如果页面有滚动条,会出现意向不到的情况:
当然,如果这个滚动条在我们的 body 上面,或许没有什么问题,但是,如果他出现在我们的里面的盒子的那个元素上面,那么可能会看不到,特别是在 Table 组件下面:
解决方法:我们给 Popconfirm 指定滚动元素
<Popconfirm
getPopupContainer={() => {
return document.getElementById('app-content') as HTMLElement;
}}>
删除
</Popconfirm>
document.getElementById('app-content') 是滚动元素的 id
<Popconfirm
getPopupContainer={(triggerNode ) => {
let targetElement = triggerNode;
while (targetElement.parentNode) {
// 检查是否有滚动条
const overflowY = window.getComputedStyle(targetElement).overflowY;
if (overflowY === 'auto' || overflowY === 'scroll') {
console.log('Found scrolling element:', targetElement);
break; // 找到滚动元素后退出循环
}
targetElement = targetElement?.parentNode as HTMLElement; // 向上层查找
}
return targetElement;
}}
删除
</Popconfirm>
整个组件:
function App() {
const columns = [
{
with: 200,
title: "Name",
dataIndex: "name",
},
{
title: "Age",
dataIndex: "age",
},
{
with: 200,
title: "Address",
dataIndex: "address",
},
{
with: 200,
title: "Address2",
dataIndex: "address2",
},
{
with: 200,
title: "Address3",
dataIndex: "address3",
},
{
with: 200,
title: "Address4",
dataIndex: "address4",
},
{
fixed: "right",
with: 200,
title: "Address5",
dataIndex: "address5",
},
{
fixed: "right",
title: "Action",
key: "action",
render: (_, record) => (
<Popconfirm
title="Sure to delete?"
okText="Yes"
cancelText="No"
getPopupContainer={() => {
return document.getElementById("app-content") as HTMLElement;
}}
onConfirm={() => {}}
>
<a>Delete</a>
</Popconfirm>
),
},
];
const data = [];
for (let i = 0; i < 46; i++) {
data.push({
key: i,
name: `Edward King ${i}`,
age: 32,
address: `London, Park Lane no. ${i}`,
address2: `London, Park Lane no. ${i}`,
address3: `London, Park Lane no. ${i}`,
address4: `London, Park Lane no. ${i}`,
address5: `London, Park Lane no. ${i}`,
});
}
return (
<div className="app">
{/* 这里加上 app-content */}
<div id="app-content" className="content">
<Table
columns={columns}
dataSource={data}
bordered
pagination={{}}
scroll={{ x: 1300 }}
></Table>
</div>
</div>
);
}
export default App;