我使用Ant设计表作为用户界面
我的代码出了什么问题,使用本地数据的表可以自动扩展,但这是不同的,因为fetch的结果不能自动扩展相同的代码
我错过了什么?
我无法用好的语言解释,看看我的沙盒https://codesandbox.io/s/defaultexpandallrows-antd-table-f1okb
此代码将自动展开
const data = [
{
key: 55,
name: "John Brown sr.",
xchildren: [
{ key: 73, address: "New York No. 2 Lake Park" },
{ key: 46, address: "New York No. 2 Lake Park" },
],
},
];
<Table
dataSource={data}
defaultExpandAllRows={true}
key={data.key}
expandable={{
expandedRowRender: (record) => (
<Table pagination={false} dataSource={record.xchildren}>
<Column title="Address" dataIndex="address" key="address" />
</Table>
),
}}
>
<Column title="name" dataIndex="name" key="key" />
</Table>
这将不会自动展开表
fetch = () => {
fetch(`https://api.jsonbin.io/b/61e6fd62ba87c130e3eaa7ef`)
.then((res) => res.json())
.then((data) => {
console.log(data);
this.setState({
dataJSON: data,
});
});
};
<Table
<Table
dataSource={dataJSON}
defaultExpandAllRows={true}
key={data.key}
expandable={{
expandedRowRender: (record) => (
<Table dataSource={record.xchildren}>
<Column
pagination={false}
title="Address"
dataIndex="address"
key="address"
/>
</Table>
),
}}
>
<Column title="name" dataIndex="name" key="key" />
</Table>
全码
import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import { Table,version } from "antd";
const { Column } = Table;
const data = [
{
key: 55,
name: "John Brown sr.",
xchildren: [
{ key: 73, address: "New York No. 2 Lake Park" },
{ key: 46, address: "New York No. 2 Lake Park" },
],
},
];
class App extends React.Component {
state = {
dataJSON: [],
};
componentDidMount() {
const { pagination } = this.state;
this.fetch({ pagination });
}
fetch = () => {
fetch(`https://api.jsonbin.io/b/61e6fd62ba87c130e3eaa7ef`)
.then((res) => res.json())
.then((data) => {
console.log(data);
this.setState({
dataJSON: data,
});
});
};
render() {
const { dataJSON } = this.state;
return (
<>
antd version: {version}
<p>will automatically expand</p>
<Table
dataSource={data}
defaultExpandAllRows={true}
key={data.key}
expandable={{
expandedRowRender: (record) => (
<Table pagination={false} dataSource={record.xchildren}>
<Column title="Address" dataIndex="address" key="address" />
</Table>
),
}}
>
<Column title="name" dataIndex="name" key="key" />
</Table>
<hr />
<p> will not automatically expand</p>
<Table
dataSource={dataJSON}
defaultExpandAllRows={true}
key={data.key}
expandable={{
expandedRowRender: (record) => (
<Table dataSource={record.xchildren}>
<Column
pagination={false}
title="Address"
dataIndex="address"
key="address"
/>
</Table>
),
}}
>
<Column title="name" dataIndex="name" key="key" />
</Table>
</>
);
}
}
ReactDOM.render(<App />, document.getElementById("container"));
2条答案
按热度按时间z9ju0rcb1#
你的问题是因为你的
dataJSON
在第一次渲染中是空的,所以antd
不能识别哪些行应该在下一次渲染中扩展,要解决这个问题有几个解决方案:1-仅当
dataJSON
已填充时才呈现表,如下所示:2-在
expandable
配置中通过expandedRowKeys
属性控制扩展行,如下所示:bn31dyow2#
您可以使用自定义钩子:
带工作台的组件: