如何在React MUI Tooltip中添加主标签与子标签双行文本
在React中实现MaterialUI Tooltip双行文本效果
要实现Tooltip的双行文本效果,核心是利用MaterialUI Tooltip的title属性支持React节点的特性,将两行内容封装为布局组件传入即可。以下是修改后的完整代码及关键说明:
关键修改点
- 将
Tooltip的title属性从单一文本替换为包含两行内容的Box组件,通过flexDirection: 'column'实现垂直排列 - 分别渲染主标签(带统计数值的国际化文本)和子标签(提示文本)
- 保留原有样式逻辑,确保Tooltip外观与
TooltipCardPopper定义一致
修改后的完整代码
import { Box, Popper, Tooltip, Typography } from '@mui/material'; import { styled } from '@mui/material/styles'; import { useTheme } from '@mui/styles'; import { useIntl } from 'react-intl'; // 复用原有TooltipCard样式 const TooltipCardPopper = styled(Popper)(({ theme }) => ({ '& > div': { ...theme.typography.caption, backgroundColor: 'white', boxShadow: theme.shadows[7], borderRadius: '5px', paddingLeft: theme.spacing(1.2), paddingRight: theme.spacing(1.2), paddingTop: theme.spacing(0.5), paddingBottom: theme.spacing(0.5), borderWidth: 1, borderStyle: 'solid', borderColor: theme.palette.grey[300], }, })); const calculateTotals = ({ data }) => data?.reduce(function (accumulator, item) { return accumulator + item.total; }, 0); const CenteredMetricToolTip = ({ position, data }) => { const theme = useTheme(); const intl = useIntl(); const show = !!position; const total = calculateTotals({ data }); return ( <Tooltip open={show} disableFocusListener disableHoverListener disableTouchListener disableInteractive title={ <Box sx={{ display: 'flex', flexDirection: 'column', gap: theme.spacing(0.3) }}> {/* 主标签行 */} <Typography variant="caption"> {intl.formatMessage( { defaultMessage: 'Self-assessment opened: {total}' }, { total }, )} </Typography> {/* 子标签行 */} <Typography variant="caption" sx={{ color: theme.palette.text.secondary }}> {intl.formatMessage({ defaultMessage: 'Click to drill down' })} </Typography> </Box> } PopperComponent={TooltipCardPopper} TransitionProps={{ timeout: 0 }} > <Box sx={{ position: 'absolute', display: show ? 'block' : 'none', // 修正原代码的hide为标准CSS属性值 left: `${position?.x ?? 0}px`, top: `${position?.y ?? 0}px`, }} > {intl.formatMessage( { defaultMessage: 'Self-assessment opened: {total}' }, { total }, )} </Box> </Tooltip> ); }; export default CenteredMetricToolTip;
额外优化说明
- 修正原代码中
display: 'hide'为display: 'none',符合CSS标准 - 为子标签添加次级文本颜色,区分主次内容(可根据Figma设计调整)
- 使用
gap属性控制两行文本间距,保持布局紧凑美观
内容的提问来源于stack exchange,提问作者Jakub
相关产品推荐
相关产品推荐

