Как создать всплывающую подсказку для строки ag-grid?

Я хочу отобразить всплывающую подсказку, основанную на status поле, при наведении на весь ряд (не только на ячейки). В документации API я нашел это: https://www.ag-grid.com/javascript-grid-column-properties/

Всплывающая подсказка Обратный вызов, который принимает (value, valueFormatted, data, node, colDef, rowIndex и api). Он должен возвращать строку, используемую в качестве всплывающей подсказки. tooltipField имеет приоритет.

Может ли это использоваться для отображения всплывающей подсказки на всю строку? Если да, может ли кто-нибудь привести какой-нибудь рабочий пример? Если нет, есть ли другой способ, которым я могу достичь этого?

Спасибо

5 ответов

Я использую их так в определении столбца:

{
    field: 'fullAddress',
    headerName: 'Address',
    tooltip: (params) => 'Address: ' + params.value
}

Начиная с версии 20.1, colDef.tooltipустарела. Теперь вы можете установить всплывающую подсказку для каждого столбца, выполнив следующие действия:

{
    field: 'ItemDescription',
    headerName: 'Description',
    tooltipField: 'ItemDescription'
}

Вы можете посмотреть документацию здесь.

Я нашел что-то вроде этого:

gridOptions.defaultColDef = {
    tooltip: (params) => {
        if (condition2) {
            return "Some txt";
        } else if (condition2) {
            return "Some txt2";
        } else {
            return "Some txt3";
        }
    }
};

Он добавит эту подсказку в качестве определений столбцов по умолчанию, поэтому вам не нужно копировать ее в каждом определении столбца.

-> ссылка на документацию: https://www.ag-grid.com/javascript-grid-cell-editing/

При необходимости используйте tooltipValueGetter:

      {
        headerName: 'Operator',
        headerTooltip: 'Operator First name and Last name',
        ...
        tooltipValueGetter (params: ITooltipParams){
                  let getterRes: string = '';
                  if (params?.data?.firstName || params?.data?.lastName) {
                    getterRes = params.data.firstName;
                    if (params?.data?.lastName) {
                      getterRes += ' ' + params.data.lastName;
                    }
                  }
                  return getterRes;
                },
        ....
}

Я создал собственный компонент всплывающей подсказки и отрендерил что-то ниже

CustomTooltip.js

      import React, { useState, useCallback } from 'react'
import ErrorOutlineOutlinedIcon from '@material-ui/icons/ErrorOutlineOutlined'
import {
    makeStyles,
    createStyles,
    withStyles,
} from '@material-ui/core/styles'
import Typography from '@material-ui/core/Typography'
import {
    Popper,
    Fade,
    Paper,
    IconButton,
    Divider,
    Link
} from '@material-ui/core'
import CancelIcon from '@material-ui/icons/Cancel'


const imageStyles = { root: { color: 'deeppink', height: 20, marginBottom: 0, width: 20 } }

const Image = withStyles(imageStyles)(({ classes }) => (
    <ErrorOutlineOutlinedIcon classes={classes} />
))

const useStylesBootstrap = makeStyles({
    arrow: {
        '&': {
            '&::before': {
                borderColor: 'lightgray transparent transparent transparent',
                borderWidth: '1em 1em 0 1em'
            },
            bottom: 0,
            height: '1em',
            left: 0,
            marginBottom: '0.5em',
            width: '2em'
        },
        '&::before': {
            borderStyle: 'solid',
            content: '""',
            display: 'block',
            height: 0,
            margin: 'auto',
            width: 0
        },
        fontSize: 9,
        position: 'absolute'
    }
})

const useStyles = makeStyles(theme =>
    createStyles({
        closeButton: {
            cursor: 'pointer',
            position: 'absolute',
            right: -8,
            top: -8
        },
        content: {
            border: `1px solid ${theme.palette.grey[300]}`,
            marginBottom: 13,
            minWidth: 500,
            padding: 0,
            zIndex: 1,
        },
        contentInner: {
            padding: theme.spacing(2)
        },
        header: {
            backgroundColor: 'deeppink',
            fontWeight: 'bold',
            padding: theme.spacing(1),
        }
    })
)

export default function SimplePopoverTooltip(params) {
    // const { arrow, ...classes } = useStylesBootstrap()
    console.log(params.column.colDef.headerName, 'params')
    const { arrow } = useStylesBootstrap()
    const classes1 = useStyles()

    // const classes = useStyles()
    const [ anchorEl, setAnchorEl ] = useState(null)
    const [ arrowRef, setArrowRef ] = useState(null)
    const [ displayArrow, setDisplayArrow ] = useState(false)

    const handleClick = useCallback(event => {
        setAnchorEl(anchorEl ? null : event.currentTarget)
        setDisplayArrow(!displayArrow)
    })
    const open = Boolean(anchorEl)
    const id = open ? 'simple-popover' : undefined
    const labelDisplay = params.value
    return (
        <div>
            <Paper
                aria-describedby={id}
                color='primary'
                onMouseEnter={handleClick}'
                style={{ alignItems: 'center', boxShadow: 'none', display: 'flex', fontSize: '12px', justifyContent: 'space-around', padding: '0px', textTransform: 'none', width: '100%'}}
            >
                {labelDisplay && labelDisplay.length > 2 ? `${labelDisplay.slice(0, 23)}...` : ''}
                {labelDisplay && labelDisplay.length > 20 ? <Image/> : ''}
            </Paper>
            <Popper
                id={id}
                open={open}
                placement='top'
                anchorEl={anchorEl}
                style={{zIndex: 1}}
                popperOptions={{
                    modifiers: {
                        arrow: {
                            element: arrowRef,
                            enabled: Boolean(arrowRef),
                        },
                    },
                }}
                transition
            >
                {useCallback(({ TransitionProps }) => (
                    <>
                        <Fade {...TransitionProps} timeout={350}>
                            <Paper className={classes1.content}>
                                <IconButton
                                    onClick={handleClick}
                                    className={classes1.closeButton}
                                >
                                    <CancelIcon style={{ width: 20 }} />
                                </IconButton>
                                <div className={classes1.header}>
                                    <Typography color='inherit' variant='body1' style={{color: 'white', fontSize: '20px'}}>
                                        {params.column.colDef.headerName}
                                    </Typography>
                                </div>
                                <Divider />
                                <div className={classes1.contentInner}>
                                    {params.value}
                                </div>
                            </Paper>
                        </Fade>
                        <Fade in={displayArrow} timeout={350}>
                            <span className={arrow} ref={setArrowRef} />
                        </Fade>
                    </>
                ), [ ])}
            </Popper>
        </div>
    )
}

Определение столбца:

      columnDefs: [{
            cellRenderer: SimplePopoverTooltip,
            field: 'action',
            filter: 'agTextColumnFilter',
            headerName: 'Action',
        },]
Другие вопросы по тегам