reactjs - 如何将 ag-grid-react 包装到组件中?
问题描述
我将 React 与 Redux 一起使用。我有一张用 ag-grid 制作的表格,用于反应。表格数据可以在线编辑和保存。
如何为该表创建包装器组件?我需要有多个具有相同功能的表,只是具有不同的数据。
在 ag-grid文档中,它展示了如何使用 redux store 和 reducers 来实现,但是这个解决方案只适用于一个表,因为我们每个应用程序只有一个状态。我不想仅仅因为我有两个不同的数据列表就复制我的代码......
解决方案
这是一个简单的例子
// Grid.jsx
import React, {
PureComponent,
} from 'react';
import {
AgGridReact,
} from 'ag-grid-react';
class Grid extends PureComponent {
state = {
columnDefs : [],
rowData : []
};
/**
* This will set your internal columnDefs & rowData
* from the props being passed in
* <Grid columnDefs={columnDefs} rowData={rowData} />
*/
static getDerivedStateFromProps(nextProps) {
const {
columnDefs,
rowData,
} = nextProps;
return {
columnDefs,
rowData,
};
}
render() {
const {
columnDefs,
rowData,
} = this.state;
return (
<AgGridReact
columnDefs={columnDefs}
rowData={rowData}
/>
);
}
}
export default Grid;
// ExampleImpl.jsx
import Grid from './Grid';
class ExampleImpl extends PureComponent {
render() {
// Assuming you got these from the connect
const rowData: [
{
name: "Ireland",
continent: "Europe",
language: "English",
code: "ie",
population: 4000000,
summary: "Master Drinkers"
},
];
const columnDefs: [
{
headerName: "Name",
field: "name",
cellRenderer: countryCellRenderer
},
{
headerName: "Continent",
field: "continent",
width: 150
},
{
headerName: "Language",
field: "language",
width: 150
}
];
return <Grid
rowData = {rowData}
columnDefs = {columnDefs}
/>
}
}
export default connect(ExampleImpl);
// ExampleImplII.jsx
import Grid from './Grid';
class ExampleImplII extends PureComponent {
render() {
// Assuming you got these from connect
const rowData: [
{
name: "Ireland",
continent: "Europe",
language: "English",
code: "ie",
population: 4000000,
summary: "Master Drinkers"
},
];
const columnDefs: [
{
headerName: "Name",
field: "name",
cellRenderer: countryCellRenderer
},
{
headerName: "Continent",
field: "continent",
width: 150
},
{
headerName: "Language",
field: "language",
width: 150
}
];
return <Grid
rowData={rowData}
columnDefs={columnDefs}
/>
}
}
export default connect(ExampleImplII);
这样,您就有 1 个展示组件和 2 个容器组件(智能组件),它们知道如何获取数据并将其传递给您的展示组件。
推荐阅读
- reactjs - 为什么它不起作用,函数调用和模块导入?
- python - 最有效的带有 if 语句的 Python 循环
- c - My function aren't working after i called them
- javascript - Sqlite 等待数据库打开
- javascript - 仅检查输入数字
- flutter - Flutter StreamBuilder ListView在流数据更改时不会重新加载
- amazon-web-services - 使用 react-native-aws3 上传到 S3
- multithreading - 异步函数 react-native 的问题
- sql-server - 类型的 SQL 等效项(如类型脚本/流类型)?
- latex - 背面页面布局不尊重 main.tex