React show Material-UI 工具提示仅适用于带有省略号的文本

React show Material-UI Tooltip only for text that has ellipsis

正在寻找一种方法让 material-ui 的工具提示在 table 单元格中展开文本 ONLY 如果文本被省略号截断(溢出)。

目前在我的 table 我有这样一个单元格:

<TableCell className={classes.descriptionCell}>{row.description}</TableCell>

我的 descriptionCell 样式是这样的:

    descriptionCell: {
        whiteSpace: 'nowrap',
        maxWidth: '200px',
        overflow: 'hidden',
        textOverflow: 'ellipsis'
    }

这使得文本在 table 中按照我希望的方式运行,但我希望能够悬停并在工具提示中查看其余部分,最好是 Material- UI 的 built 在工具提示组件中。

我知道这里有一个包 https://www.npmjs.com/package/react-ellipsis-with-tooltip 应该可以做到这一点,但它使用 bootstrap 工具提示,而不是 material UI.

请找到下面的代码和框 - https://codesandbox.io/s/material-demo-p2omr

我在这里使用 ref 获取 TableCell DOM 节点,然后比较 scrollWidth 和 clientWidth 以确定是否必须显示 Tooltip。(这是基于答案 here

我已将 "rowref"(属性 具有参考)和 "open"(disable/enable 工具提示)添加为行的新属性。我不知道您的数据来自哪里,但我假设您可以将这些属性添加到行中。

还有一点要注意,我只是设置 "disableHoverListener" 属性来禁用 tooltip 。还有其他道具 - "disableFocusListener" & "disableTouchListener" ,如果你想使用那些。更多信息 here

希望这对你有用。如果您对代码有任何疑问,请告诉我。

我 运行 今天遇到了同样的问题,@vijay-menon 的回答很有帮助。这是一个用于同一事物的简单独立组件:

import React, { Component } from 'react';
import Tooltip from '@material-ui/core/Tooltip';

class OverflowTip extends Component {
    constructor(props) {
        super(props);
        this.state = {
            overflowed: false
        };
        this.textElement = React.createRef();
    }

    componentDidMount () {
        this.setState({
            isOverflowed: this.textElement.current.scrollWidth > this.textElement.current.clientWidth
        });
    }

    render () {
        const { isOverflowed } = this.state;
        return (
            <Tooltip
                title={this.props.children}
                disableHoverListener={!isOverflowed}>
                <div
                    ref={this.textElement}
                    style={{
                        whiteSpace: 'nowrap',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis'
                    }}>
                    {this.props.children}
                </div>
            </Tooltip>
        );
    }
}

用法示例:

<OverflowTip>
      some long text here that may get truncated based on space
</OverflowTip>

一个麻烦是,如果元素的 space 在页面中动态更改(例如页面调整大小或动态 DOM 更改),它不会确认新的 space并重新计算是否溢出。

Tippy 等其他工具提示库有一个方法,当尝试 打开工具提示时会触发该方法。这是进行溢出检查的完美位置,因为它始终有效,无论文本元素的 DOM 宽度是否已更改。不幸的是,使用 Material UI.

提供的 API 比较麻烦

结束@benjamin.keen 的回答。这是一个独立的功能组件,它只是他使用挂钩执行比较功能的答案的扩展。

import React, { useRef, useEffect, useState } from 'react';
import Tooltip from '@material-ui/core/Tooltip';
const OverflowTip = props => {
  // Create Ref
  const textElementRef = useRef();

  const compareSize = () => {
    const compare =
      textElementRef.current.scrollWidth > textElementRef.current.clientWidth;
    console.log('compare: ', compare);
    setHover(compare);
  };

  // compare once and add resize listener on "componentDidMount"
  useEffect(() => {
    compareSize();
    window.addEventListener('resize', compareSize);
  }, []);

  // remove resize listener again on "componentWillUnmount"
  useEffect(() => () => {
    window.removeEventListener('resize', compareSize);
  }, []);

  // Define state and function to update the value
  const [hoverStatus, setHover] = useState(false);

  return (
    <Tooltip
      title={props.value}
      interactive
      disableHoverListener={!hoverStatus}
      style={{fontSize: '2em'}}
    >
      <div
        ref={textElementRef}
        style={{
          whiteSpace: 'nowrap',
          overflow: 'hidden',
          textOverflow: 'ellipsis'
        }}
      >
        {props.someLongText}
      </div>
    </Tooltip>
  );
};

export default OverflowTip;

基于benjamin.keen回答,这是他的代码的功能版本:

import React, { useRef, useState, useEffect } from 'react';
import Tooltip from '@material-ui/core/Tooltip';

const OverflowTip = ({ children }) => {
  const [isOverflowed, setIsOverflow] = useState(false);
  const textElementRef = useRef();
  useEffect(() => {
    setIsOverflow(textElementRef.current.scrollWidth > textElementRef.current.clientWidth);
  }, []);
  return (
    <Tooltip title={children} disableHoverListener={!isOverflowed}>
      <div
        ref={textElementRef}
        style={{
          whiteSpace: 'nowrap',
          overflow: 'hidden',
          textOverflow: 'ellipsis',
        }}
      >
        {children}
      </div>
    </Tooltip>
  );
};

基于@Dheeraj 的回答——这与他的组件非常接近,但在类型脚本版本中更有意义的道具名称:

import React, { useRef, useEffect, useState } from 'react';
import Tooltip from '@material-ui/core/Tooltip';

interface Props {
  tooltip: string;
  text: string;
}

const OverflowTooltip = (props: Props) => {

  const textElementRef = useRef<HTMLInputElement | null>(null);

  const compareSize = () => {
    const compare =
      textElementRef.current.scrollWidth > textElementRef.current.clientWidth;
    setHover(compare);
  };

  useEffect(() => {
    compareSize();
    window.addEventListener('resize', compareSize);
  }, []);

  useEffect(() => () => {
    window.removeEventListener('resize', compareSize);
  }, []);

  const [hoverStatus, setHover] = useState(false);

  return (
    <Tooltip
      title={props.tooltip}
      interactive
      disableHoverListener={!hoverStatus}
    >
      <div
        ref={textElementRef}
        style={{
          whiteSpace: 'nowrap',
          overflow: 'hidden',
          textOverflow: 'ellipsis',
        }}
      >
        {props.text}
      </div>
    </Tooltip>
  );
};

export default OverflowTooltip;

我们这样使用它:

<OverflowTooltip 
    tooltip={'tooltip message here'}
    text={'very long text here'}
/>

定义文本是否溢出的方法在接受的答案中有缺陷。由于 scrollWidthclientWidth return 四舍五入的整数值,当它们之间的差异很小时,我们将得到相等的值并且工具提示将不起作用。问题是省略号也算作 clientWidth,所以当我们只有一个或 tho 个字符溢出时,我们会看到省略号,但 scrollWidthclientWidth 是相等的。 以下是对我有用的解决方案,可以确定 scrollWidthclientWidth 的分数精度并解决了这个问题:

import React, { useRef, useState, useEffect } from 'react';
import { Tooltip } from '@material-ui/core';

const OverflowTooltip = ({ children }) => {
    const textElementRef = useRef();
    
    const checkOverflow = () => {
        // Using getBoundingClientRect, instead of scrollWidth and clientWidth, to get width with fractional accuracy
        const clientWidth = textElementRef.current.getBoundingClientRect().width

        textElementRef.current.style.overflow = 'visible';
        const contentWidth = textElementRef.current.getBoundingClientRect().width
        textElementRef.current.style.overflow = 'hidden';

        setIsOverflow(contentWidth > clientWidth);
    }
    
    useEffect(() => {
        checkOverflow();
        window.addEventListener('resize', checkOverflow)
        return () => {
            window.removeEventListener('resize', checkOverflow)
        }
    }, []);
    
    const [isOverflowed, setIsOverflow] = useState(false);
    
  return (  
    <Tooltip title={children} disableHoverListener={!isOverflowed}>       
      <span ref={textElementRef}
            style={{
                whiteSpace: 'nowrap',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
            }}
        >
            {children}
      </span>
    </Tooltip>
  );
};
export default OverflowTooltip

如果您只想在内容溢出时显示工具提示,这将起作用。

useEffect() 是必需的,因为 ref.current 最初是空的,但是当组件安装时它被设置,你可以根据它获取 html 元素。

interface MyInterface {
    content: Content;
}

export const MyComponent: React.FC<MyInterface> = ({ content }) => {
const ref = useRef(null);

const [showTooltip, setShowTooltip] = useState(false);

useEffect(() => {
    if (!ref.current) return;

    const div = ref.current as HTMLDivElement;
    const isOverflow = div.offsetWidth < div.scrollWidth;
    setShowTooltip(isOverflow);
}, []);

const renderContent = () => (
    <div ref={ref}>
        content
    </div>
);

return (
    <>
        {ref.current && showTooltip ? (
            <Tooltip title={content.value}>
                {renderContent()}
            </Tooltip>
        ) : (
            renderContent()
        )}
    </>
);

};

如果有人需要 TypeScript 版本:

import { Tooltip, Typography, TypographyProps } from "@mui/material";
import { FC, ReactChild, useEffect, useRef, useState } from "react";

export interface OverflowTypograpyProps extends TypographyProps {
  children: ReactChild;
}

export const OverflowTypograpy: FC<OverflowTypograpyProps> = ({
  children,
  ...props
}) => {
  const ref = useRef<HTMLSpanElement>(null);
  const [tooltipEnabled, setTooltipEnabled] = useState(false);

  useEffect(() => {
    const compareSize = () => {
      if (ref.current) {
        const compare = ref.current.scrollWidth > ref.current.clientWidth;

        setTooltipEnabled(compare);
      }
    };
    compareSize();
    window.addEventListener("resize", compareSize);
    return () => window.removeEventListener("resize", compareSize);
  }, []);

  return (
    <Tooltip title={children} disableHoverListener={!tooltipEnabled}>
      <Typography
        ref={ref}
        noWrap
        overflow="hidden"
        textOverflow="ellipsis"
        {...props}
      >
        {children}
      </Typography>
    </Tooltip>
  );
};

我认为您不需要了解任何副作用钩子。顶部 post 建议在 window 上放置一个事件侦听器,它会在每次鼠标移动事件时触发。我们可以只定义一些回调并将它们传递给 onMouseEnteronMouseLeave

import React, { useState, MouseEvent } from "react";
import Tooltip, { TooltipProps } from "@mui/material/Tooltip";

export const OverflowTooltip = ({ children, ...props }: TooltipProps) => {
  const [tooltipEnabled, setTooltipEnabled] = useState(false);

  const handleShouldShow = ({ currentTarget }: MouseEvent<Element>) => {
    if (currentTarget.scrollWidth > currentTarget.clientWidth) {
      setTooltipEnabled(true);
    }
  };

  const hideTooltip = () => setTooltipEnabled(false);

  return (
    <Tooltip
      onMouseEnter={handleShouldShow}
      onMouseLeave={hideTooltip}
      disableHoverListener={!tooltipEnabled}
      {...props}
    >
      <div
        style={{
          whiteSpace: 'nowrap',
          overflow: 'hidden',
          textOverflow: 'ellipsis',
        }}
      >
        {children}
      </div>
      {children}
    </Tooltip>
  );
};