React AG Grid v18 Beta版本表格自定义悬浮Tooltip组件方案
AG Grid v18 Beta 自定义Tooltip 实现方案
你的代码无法生效的核心原因是:AG Grid v18 Beta 并不支持 tooltipComponent 这个配置项,该属性是在后续版本(v20+)才引入的。要在v18中实现自定义React Tooltip,需要适配该版本的API:
关键修改点
- 开启全局Tooltip功能:必须显式设置
enableTooltips={true}(v18默认关闭此功能) - 列定义替换配置项:用
tooltipRenderer替代新版的tooltipComponent - 自定义组件参数适配:v18中组件接收的是
params对象,需从中提取单元格值、行数据等信息
修改后的完整代码
1. CustomTooltip.js
import React from 'react'; const CustomTooltip = ({ params }) => { // 从params对象中获取当前单元格的值,params还包含整行数据、列信息等 const value = params.value; return ( <div style={{ padding: '10px', backgroundColor: 'rgba(0,0,0,0.7)', color: 'white', borderRadius: '5px' }}> <p><strong>Data Volume:</strong> {value}%</p> </div> ); }; export default CustomTooltip;
2. MyAgGrid.js
import React, { Component } from 'react'; import { AgGridReact } from 'ag-grid-react'; import 'ag-grid-community/styles/ag-grid.css'; import 'ag-grid-community/styles/ag-theme-alpine.css'; import CustomTooltip from './CustomTooltip'; class MyAgGrid extends Component { constructor(props) { super(props); this.state = { columnDefs: [ { headerName: 'Country', field: 'country', width: 170, cellStyle: { fontSize: '16px' }, }, { headerName: 'Severity', field: 'severity', width: 130, cellStyle: { fontSize: '16px' }, }, { headerName: 'Data Volume', field: 'dataVol', width: 210, // v18使用tooltipRenderer指定已注册的自定义组件 tooltipRenderer: 'customTooltip', }, { headerName: 'Timestamp', field: 'timestamp', width: 150, }, ], rowData: [ { country: 'india', severity: 'High', dataVol: 10, timestamp: '2023-09-11' }, { country: 'japan', severity: 'High', dataVol: 1, timestamp: '2023-09-10' }, { country: 'china', severity: 'High', dataVol: 0, timestamp: '2023-09-09' }, ], frameworkComponents: { customTooltip: CustomTooltip, } }; } render() { const { columnDefs, rowData, frameworkComponents } = this.state; return ( <div className="ag-theme-alpine" style={{ height: '400px', width: '600px' }}> <AgGridReact columnDefs={columnDefs} rowData={rowData} frameworkComponents={frameworkComponents} domLayout="autoHeight" // 必须显式开启Tooltip功能 enableTooltips={true} /> </div> ); } } export default MyAgGrid;
扩展说明
如果需要展示更多行数据信息(如关联的国家名称),可以直接从params.data中提取整行数据:
const { dataVol, country } = params.data; return ( <div style={{ padding: '10px', backgroundColor: 'rgba(0,0,0,0.7)', color: 'white', borderRadius: '5px' }}> <p><strong>Country:</strong> {country}</p> <p><strong>Data Volume:</strong> {dataVol}%</p> </div> );
内容的提问来源于stack exchange,提问作者Harish Mahi
相关产品推荐
相关产品推荐

