如何隐藏小型设备的AND数据表列(移动视图)?



如果表格有五列,我只想显示 2 列用于移动视图

https://ant.design/components/table

您可以将列保持在组件状态,并在调整窗口大小时动态筛选列。像这样的东西

useEffect(() => {
window.addEventListener("resize", <callback function to update columns>);
// cleanup
return() => window.removeEventListener("resize");
});

在渲染方法中,您需要使用let声明列,并在 window.innerWidth <480 时更改它们(为了安全起见,我将其小于 500 px(。通过更改,我的意思是仅从列数组中筛选所需的列。筛选的最佳方法是按键,因为它是唯一的。这是代码的反应方式:

import React, { PureComponent } from "react";
import { Table } from "antd";
export default class MainPage extends PureComponent {
renderMobileTable = columns => {
return columns.filter(
column => column.key === "name" || column.key === "city"
);
};
render() {
const dataSource = [
{
key: "1",
name: "Mike",
lastName: "Willins",
age: 32,
address: "10 Downing Street",
city: "Chicago"
},
{
key: "2",
name: "John",
lastName: "Billards",
age: 42,
address: "5th Blvd",
city: "New York"
}
];
let columns = [
{
title: "Name",
dataIndex: "name",
key: "name"
},
{
title: "Last Name",
dataIndex: "lastName",
key: "lastName"
},
{
title: "Age",
dataIndex: "age",
key: "age"
},
{
title: "Address",
dataIndex: "address",
key: "address"
},
{
title: "City",
dataIndex: "city",
key: "city"
}
];
const isMobile = window.innerWidth < 500;
if (isMobile) {
columns = this.renderMobileTable(columns);
}
return <Table dataSource={dataSource} columns={columns} />;
}
}

有关源代码,您可以参考我在 GitHub 上的存储库。

注意:如果您要在 Chrome 开发工具中测试移动视图,请确保在调整大小后重新加载页面,因为我们将逻辑放入 render 方法中,并且必须重新呈现或重新加载应用程序。

在antd v4中,您可以使用列prop"响应式">

const columns = [{
title: 'identification number',
dataIndex: 'ID',
responsive: ['sm'],
}]

https://ant.design/components/table/#Column

也许您不需要隐藏移动视图上的列。另一种解决方案:只需将x滚动条添加到表中:

<Table scroll={{ x: "max-content" }} />

通过添加此内容,表格将仅占用必要的宽度,并且将显示一个x滚动条,供用户在较小的设备上水平滚动表格。

最新更新