参考Ag grid react官网上的方法先实现一个表格React Data Grid: Get Started with AG Grid
代码如下:
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import AgGridRender from './AgGridRender';
ReactDOM.render(
<React.StrictMode>
<AgGridRender/>
</React.StrictMode>,
document.getElementById('root')
)
AgGridRender.js
import React, {
useState,
} from 'react';
import {AgGridReact} from 'ag-grid-react';
import './AgGridRender.css';
import 'ag-grid-community/styles/ag-grid.css';
import 'ag-grid-community/styles/ag-theme-alpine.css';
const AgGridRender = () => {
const [columnDefs] = useState([
{field: 'make', filter: true},
{field: 'model', filter: true},
{field: 'price'}
]);
const [rowData] = useState([
{make: 'Toyota', model: 'Celica', price: 35000},
{make: 'Ford', model: "Mondeo", price: 32000},
{make: "Porsche", model: "Boxster", price: 72000}
]);
return (
<div className="ag-theme-alpine">
<AgGridReact
rowData={rowData}
columnDefs={columnDefs}
/>
</div>
)
}
export default AgGridRender;
AgGridRender.css
.ag-theme-alpine {
width: 100vw;
height: 100vh;
}
接下来实现宽度的自适应
用到的主要方法是sizeColumnsToFit
代码如下:
import React, {
useState,
useRef,
useCallback,
useEffect
} from 'react';
import {AgGridReact} from 'ag-grid-react';
import './AgGridRender.css';
import 'ag-grid-community/styles/ag-grid.css';
import 'ag-grid-community/styles/ag-theme-alpine.css';
const AgGridRender = () => {
const [columnDefs] = useState([
{field: 'make', filter: true},
{field: 'model', filter: true},
{field: 'price'}
]);
const [rowData] = useState([
{make: 'Toyota', model: 'Celica', price: 35000},
{make: 'Ford', model: "Mondeo", price: 32000},
{make: "Porsche", model: "Boxster", price: 72000}
]);
const parentRef = useRef();
const resizeRef = useRef();
const widthRef = useRef();
useEffect(()=>{
window.addEventListener("resize", resize);
return () => {
window.removeEventListener("resize", resize);
}
}, [rowData]);
const onFirstDataRendered = (params) => {
params.api.sizeColumnsToFit();
}
const resize = useCallback(() => {
if(parentRef.current?.getBoundingClientRect().width !== widthRef.current) {
if(resizeRef.current) {
clearTimeout(resizeRef.current);
}
resizeRef.current = setTimeout(() => {
if(parentRef.current) {
const {width} = parentRef.current.getBoundingClientRect();
widthRef.current = width;
resizeRef.current = null;
agRef.current.api.sizeColumnsToFit();
}
}, 200);
}
}, []);
return (
<div className="ag-theme-alpine" ref={parentRef}>
<AgGridReact
rowData={rowData}
columnDefs={columnDefs}
onFirstDataRendered={onFirstDataRendered}
/>
</div>
)
}
export default AgGridRender;
实现的效果如下: